Examples of expressions and precedence

The parentheses in the following expressions explicitly show how the compiler groups operands and operators.

total = (4 + (5 * 3));
total = (((8 * 5) / 10) / 3);
total = (10 + (5/3));

If parentheses did not appear in these expressions, the operands and operators would be grouped in the same manner as indicated by the parentheses. For example, the following expressions produce the same output.

total = (4+(5*3));
total = 4+5*3;

Because the order of grouping operands with operators that are both associative and commutative is not specified, the compiler can group the operands and operators in the expression:

total = price + prov_tax +
city_tax;

in the following ways (as indicated by parentheses):

total = (price + (prov_tax + city_tax));
total = ((price + prov_tax) + city_tax);
total = ((price + city_tax) + prov_tax);

The grouping of operands and operators does not affect the result unless one ordering causes an overflow and another does not. For example, if price = 32767, prov_tax = -42, and city_tax = 32767, and all three of these variables have been declared as integers, the third statement total = ((price + city_tax) + prov_tax) will cause an integer overflow and the rest will not.

Because intermediate values are rounded, different groupings of floating-point operators may give different results.

In certain expressions, the grouping of operands and operators can affect the result. For example, in the following expression, each function call might be modifying the same global variables.

a = b() + c() + d();

This expression can give different results depending on the order in which the functions are called.

If the expression contains operators that are both associative and commutative and the order of grouping operands with operators can affect the result of the expression, separate the expression into several expressions. For example, the following expressions could replace the previous expression if the called functions do not produce any side effects that affect the variable a.

a = b();
a += c();
a += d();

The order of evaluation for function call arguments or for the operands of binary operators is not specified. Therefore, the following expressions are ambiguous:

z = (x * ++y) / func1(y);
func2(++i, x[i]);

If y has the value of 1 before the first statement, it is not known whether or not the value of 1 or 2 is passed to func1(). In the second statement, if i has the value of 1 before the expression is evaluated, it is not known whether x[1] or x[2] is passed as the second argument to func2().