I have done a ton of research as to how the order of evaluation goes - but cannot figure out how it would go for this equation:
z = !x + y * z / 4 % 2 - 1
My best guess is (from left to right):
z = !x + {[([y * z] / 4) % 2] - 1}
Order of evaluation of the operands of any C (does apply for Objective C and C++) operator is unspecified (except where noted below). This includs the order of evaluation of function arguments in a function-call expression and the order of evaluation of the subexpressions within any expression.
"Order of evaluation" refers to when different subexpressions within the same expression are evaulated relative to each other. you have the usual precedence rules between multiplication and addition.
Expression evaluation in C is used to determine the order of the operators to calculate the accurate output. Arithmetic, Relational, Logical, and Conditional are expression evaluations in C.
Order of evaluation and operator precedence are two different things.
Your best guess is correct. All the multiplicative operators *
/
%
have the same precedence, and bind left-to-right. The additive operator -
has lower precedence. The unary !
operator binds more tightly than the multiplicative or additive operators. And the assignment operator =
has very low precedence (but still higher than the comma operator).
So this:
z = !x + y * z / 4 % 2 - 1
is equivalent to this:
z = (!x) + (((y * z) / 4) % 2) - 1
But the operands may legally be evaluated in any order (except for certain operators like &&
, ||
, ,
, which impose left-to-right evaluation). If the operands are simple variables, this probably doesn't matter, but in something like:
z = func(x) * func(y);
the two function calls may occur in either order.
If you can't understand it, rewrite your expression
z = !x + y * z / 4 % 2 - 1
notx = !x; /* you can move this line 1, 2, or 3 lines down */
tmp1 = y * z;
tmp2 = tmp1 / 4;
tmp3 = tmp2 % 2;
tmp4 = notx + tmp3;
tmp5 = tmp4 - 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With