简体   繁体   English

C - 等式的评估顺序

[英]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}

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM