Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Order of Evaluation for equation

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}
like image 950
snakeopus121 Avatar asked Mar 06 '13 23:03

snakeopus121


People also ask

What is the order of evaluation in C?

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.

What is the order of evaluation in the 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.

What is C evaluation?

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.


2 Answers

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.

like image 149
Keith Thompson Avatar answered Oct 23 '22 03:10

Keith Thompson


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;
like image 1
pmg Avatar answered Oct 23 '22 04:10

pmg