2

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

user2578525
  • 191
  • 1
  • 11
  • possible duplicate of [Undefined behavior and sequence points](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) – phuclv Jan 31 '15 at 07:53
  • 1
    read this https://en.wikipedia.org/wiki/Sequence_point – phuclv Jan 31 '15 at 07:53

4 Answers4

3
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

Gopi
  • 19,784
  • 4
  • 24
  • 36
0

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

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
  • This seems to imply that function parameter evaluations have a defined order which I don't believe is the case in C. – tangrs Jan 31 '15 at 06:47
0

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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Unless I'm missing something obvious, I don't see a sequence point between the evaluations. Doesn't this make it undefined behaviour? – tangrs Jan 31 '15 at 06:46
  • @tangrs, It is undefined behavior. I was trying to explain the outcome reported by the OP. – R Sahu Jan 31 '15 at 06:48
  • You should probably indicate that in your last sentence since it could be misleading. – tangrs Jan 31 '15 at 06:50
0

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

kelsier
  • 4,050
  • 5
  • 34
  • 49