Order of expression evaluation in C

流过昼夜 提交于 2019-11-30 21:29:20

There is no specified order since the multiplication operator is not a sequence point. Sequence points include the comma operator, the end of a full expression, and function calls. Thus the order of evaluation of (a) and (b) is up to the compiler implementation. Therefore you shouldn't attempt to-do something in (a) that would have a side-effect that you want to be seen in (b) in order to generate a valid result.

For instance:

int a=5;
int b = (a++) * (a++); //<== Don't do this!!

If you want a full-listing of sequence points for C, you can check out a more thorough reference here.

The evaluation order of the operands of the * binary operator is unspecified in C90.

Here is the relevant paragraph from the C90 Standard (as the question asked about C90):

(C90, 6.3) "Except as indicated by the syntax or otherwise specified later (for the function-call operator (), &&, ||, ?:, and comma operators). the order of evaluation of subexpressions and the order in which side effects take place are both unspecitied"

For the * operator, if we take an example with side-effect operands like:

c =  f() * g();

the implementation can call f() first or g() first:

a = f();
b = g();
c = a * b;

or

a = g();
b = f();
c = a * b;

Both are valid translations.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!