Possible Duplicate:
confused about printf() that contains prefix and postfix operators.
I came across a code with the following snippet,
int main() {
int c = 100;
printf("\n %d \t %d \n", c, c++);
return 0;
}
I expected the output to be 100 & 101 but I get output as
101 100
Could anyone help me know why?
The C and C++ standards do not guarantee the order of evaluation of function parameters. Most compilers will evaluate parameters from right to left because that is the order they get pushed on the stack using the cdecl calling convention.
There is no guarantee whether c
on the left, or c++
on the right, will be evaluated first.
The order of evaluation of function parameters is Unspecifeid and hence Undefined Behavior as per the standard.
As per Section 1.9 of the C++ standard:
"Certain other aspects and operations of the abstract machine are described in this International Standard as unspecified
(for example, order of evaluation of arguments to a function
). Where possible, this International Standard defines a set of allowable behaviors. These define the nondeterministic aspects of the abstract machine."
If you had just used printf ("%d\n", c++)
or printf ("%d\n", c)
the result would have been 100 in either case. Printing both c and c++ in one function call as you did is undefined behavior.
printf works from right to left so first c++ is executed (c= 100) then after C++ executes and C=101 therefore 101 and 100 is output http://en.wikipedia.org/wiki/Printf
精彩评论