I don't understand what is passed to the function f() when I call it like this.
main()
{
void f(int,int);
int i=10;
f(i,i++);
}
void f(int i,int j)
{ printf("%d %d",i,j); }
gives me 11 10 .Can somebody explain why its 11?
The behavior is undefined, as follows: From the C99 standard: 6.5 Expressions We're violating the second sentence of that paragraph; we're not just reading the prior value to determine the new value to be stored. Note that undefined doesn't necessarily mean illegal. Undefined simply means that the compiler is free to handle the situation any way it sees fit; any result is considered "correct". You could very well wind up with the result you expected. Or not. The program could crash. Or not. Or anything else could happen. In this case, you will get different results based on platform, compiler, optimization settings, surrounding code, etc. The reason for that is as follows: 6.5.2.2 Function calls It is unspecified whether 6.5.2.4 Postfix increment and decrement operators Emphasis mine. Edit Changed the wording a bit to make it clear that the behavior is undefined. |
|||||||
|
Because undefined behaviour, that's why. You read the value twice and modify it once with no intervening sequence point, which is a giant pile of illegal. Even if it were not illegal, the compiler has no obligation to evaluate your function arguments in any particular order, or indeed, to even evaluate one fully before evaluating another. |
|||||||||||||||
|
The order of evaluation of function arguments is unspecified and so |
|||
|
f(i,++i);
and compared it tof(i,i++);
? – FrustratedWithFormsDesigner May 28 '12 at 18:03