Sunday, June 1, 2008

Do the parentheses always enforce desired order in C?


Question: Will the use of parentheses always enforce the desired order of evaluation in C?

Answer: No... not always! Yeah, you read it right. There are cases where the parentheses will not dictate the order of evaluation. For example: 'value = fun1() + fun2() * fun3()' in this expression, we can't ensure the order in which the three functions will be called irrespetive of whether we enclose them witihn parentheses or not. Of course, the multiplication will take place first and then only addition will be performed, but whether fun1() will be called first or fun3() or fun2(), is not specified and it depends upon the particular implementation.

How to force the call of functions to happen in a specified sequence?

You can simply have the calls in separate statements and store the results in temporary variables. which subsequently can be used to form the original expression. If we take the above example only and if we want to ensure that fun1(), fun2(), and fun3() will be called in this order only then we can do the following:-

.....
temp1 = fun1();
temp2 = fun2();
temp3 = fun3();
value = temp1 + temp2 * temp3;
.....

In this scenario, the functions will be called in the specified sequence and then the expression will be evaluated to compute the 'value'.



Share/Save/Bookmark


No comments: