operator precedence problem? [duplicate]
Possible Duplicate:
Compilers and argument order of evaluation in C++
i have a print statement like below...
int i=0;
printf("%d,%d,%d,%d,%d,%d",i开发者_Python百科++,i,++i,i--,++i,i);
according to precedence i++,i,++i,i--,++i,i
should be evaluated like below step by step...
0,i,++i,i--,++i,i // after this i=1;
0,i,++i,1,++i,i // after this i=0;
0,i,++i,1,1,i // after this i=1;
0,i,2,1,1,i // after this i=2;
0,2,2,1,1,2 // after this i=2;
and final result as i think from this logic should be...
0,2,2,1,1,2
but i am getting 2,2,2,1,2,2
what is the reason behind this?
btw i m using visual c++ 2010...
That's undefined behavior. The order of evaluation of the arguments to a function is specifically left unspecified by the C and C++ language standards in order to let the compiler produce the most optimal machine code across a broad range of hardware.
You're not allowed to modify a variable more than once between sequence points. The language standard says that sequence points only come at particular points in your code, such as at the semicolons that delimit statements. There is a sequence point after the initial assignment int i=0;
, there is a sequence point after printf
returns, and there is a sequence point after all of the arguments to printf
have been evaluated but before printf
actually gets called, but there is not a sequence point in between the evaluation of each of the arguments.
Not.
The comma operator here:
a,b;
and the comma which separates functions arguments:
f(a,b);
are different.
Only real comma operator will be a sequence point and will order evaluation of left and right arguments (a
and b
expressions in my example).
And the comma between function arguments is not a sequence point and order of argument evaluation is undefined (even same compiler may evaluate them in different order in different call sites). Also, it is illegal (undefined behaviour) to change the same lvalue (i
variable in your example) twice or more times in the part of program between sequence points. Every modification of same object must be separated by sequence point (e.g. with ;
) from another modification of the same object.
The comma in your case is not the ,
operator that guarantees evaluation in sequence, but belongs to the function call syntax and the sequence in which function arguments are evaluated is undefined. So your code should surely exhibit undefined behaviour (which it seemingly does).
It's up to the compiler what code it generates. Evaluation order of the arguments of a function call is not defined.
精彩评论