order of evaluation of function parameters

柔情痞子 提交于 2019-11-27 16:19:43

From the C++ standard:

The order of evaluation of arguments is unspecified. All side effects of argument expression evaluations take effect before the function is entered. The order of evaluation of the postfix expression and the argument expression list is unspecified.

However, your example would only have undefined behavior if the arguments were x>>=2 and x<<=2, such that x were being modified.

Bit shift operators don't modify the value of the variable... so order doesn't matter.

The order of evaluation is unspecified, but it doesn't matter because you're not modifying x at all.

So the program is well-defined, and the answer is as given.

The following would have undefined semantics:

printf("%d,%d,%d\n", x, x <<= 2, x >>= 2); 
Igor

I found the answer in c++ standards.

Paragraph 5.2.2.8:

The order of evaluation of arguments is unspecified. All side effects of argument expression evaluations take effect before the function is entered. The order of evaluation of the postfix expression and the argument expression list is unspecified.

In other words, It depends on compiler only.

The order of evaluation is undefined in the Official C Specification.

However, as a matter of practicality, parameters are usually evaluated right-to-left.

In your problem, the bit-shift operator doesn't change the value of X, so the order of evaluation is not important. You'd get 5,20,1, whether evaluated left-to-right, right-to-left, or middle-first.

In C, parameters are pushed on to the stack in a right-to-left order, so that the 1st param (in this case, the char* "%d,%d,%d") is at the top of the stack. Parameters are usually (but not always) evaluated in the same order they are pushed.

A problem that better illustrates what you're talking about is:

int i=1;
printf("%d, %d, %d", i++, i++, i++);

The official answer is "undefined".
The practical answer, (in the several compilers/platforms I've tried), is "3, 2, 1".

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