So i came across the following code in C Language
foo() {
int v=10;
printf("%d %d %d\n", v==10, v=25, v > 20);
}
and it returns 0 25 0
can anybody explain me how and why
So i came across the following code in C Language
foo() {
int v=10;
printf("%d %d %d\n", v==10, v=25, v > 20);
}
and it returns 0 25 0
can anybody explain me how and why
printf("%d %d %d\n", v==10, v=25, v > 20);
What you see is undefined behavior becuase the order of evalutaion within printf()
is not defined.
The output can be explained as(Right to left evaluation)
v = 10 and hence v>20 is false so last `%d` prints 0
v = 25 Now v is 25 so second `printf()` prints out 25
Then you have
v ==10
which is false because v is 25 now. This is not a defined order of evaluation and might vary so this is UB
It is evaluated from right to left...
First it evaluates v > 20
its false so it prints 0
Next it sets v=25
an prints it
Next it check if v is 10
. Its false so it prints 0 (the value of v
is changed in the above step)
EDIT
This is the way your compiler evaluates it but the order of evalaution generally is undefined
Your code is subject to undefined behavior. Looks like in your platform,
v > 20
got evaluated first, followed by
v=25
, followed by
v==10
.
Which is perfectly standards compliant behavior.
Remember that those expressions could have been evaluated in any order and it would still be standards compliant behavior.
Your compiler seems to evaluate the function parameters from right to left.
So, v > 20
is evaluated first, then v=25
and then v==10
.
Therefore you get the output 0 25 0