Can anyone tell me the correct procedure of evaluation of the answer (with internal working)?
#include<stdio.h>
main()
{
int a=10;
printf("%d %d %d\n",a,a++,++a);
return 0;
}
Can anyone tell me the correct procedure of evaluation of the answer (with internal working)?
#include<stdio.h>
main()
{
int a=10;
printf("%d %d %d\n",a,a++,++a);
return 0;
}
There is no single, correct behavior for this code.
Technically, ANY output or result from this program is correct, even nasal demons.
It falls into undefined behavior.
While we can guess at likely and possible outcomes, anything is allowed by the C language in this case.
Within a single portion1 of an expression, you are not permitted (within defined behavior of C) to modify an object twice or to modify an object and separately use its value.
Your expression, printf("%d %d %d\n",a,a++,++a)
, contains a
, a++
, and ++a
. This is not permitted because both a++
and ++a
modify a
. It is also not permitted because a
uses a
and a++
separately modifies a
.
Do not write code like this.
When you do this, the behavior is undefined. A compiler might evaluate these three things in any order, or it might “break” and do something completely different. You might have gotten “12 11 12“ because the code generated by the compiler did this:
a++
would have (11) and calculate the incremented value (12), but hold that value in a temporary register (do not write it to memory yet).++a
would have (12, because a
is still 11).a
, either from the temporary or from the ++a
or both.a
has (now 12).printf
.But the code might have done something else. In this case, you could tell only by examining the generated assembly code. You cannot tell from what the C standard says, because the C standard does not say what happens in this case. Examining the assembly code would only tell you what happens in this case; it may be different when the same C source code is compiled for a different processor architecture, when different compilation switches are used, or when the compiler version is changed.
1Expressions may be divided into portions by sequence points. See this answer for more about sequence points.