1

Consider code below:

#include <stdio.h>

int main()
{
    int x=0,y=5;
    printf("x=%d,x_1=%d,sum=%d",x++,x,y+x);
    return 0;
}

My assumption on this code was that, x would be printed as 0 and later on postincrement x_1 would be 1 and y+x be 5+1=6

Actual result is x as 0 as expected , x_1 as 1 as expected. But y+x be 5. I am unsure why x retains its previous value though an postincrement had occured. Could you please help clarify this? I used gcc compiler for the same.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Gayathri
  • 1,776
  • 5
  • 23
  • 50
  • You will never undertand code like `printf("x=%d,x_1=%d,sum=%d",x++,x,y+x);`, because there is "too much going on". But if you break it up into three separate calls: `printf("x=%d,",x++); printf("x_1=%d,",x); printf("sum=%d\n",y+x); ` it should make sense. – Steve Summit Nov 01 '19 at 12:15
  • @SteveSummit This is just a different trial. I know behavior would be as expected if they were written separately. – Gayathri Nov 04 '19 at 06:03

2 Answers2

1

In

printf("x=%d,x_1=%d,sum=%d", x++, x, y+x);
//                           (a) (b)  (b)

you are both updating x (a) and using its value (b) in the same expression (with no intervening sequence point).
That's Undefined Behaviour.

Try

printf("x=%d,x_1=%d,sum=%d", x, x + 1, y + x + 1);
x++;
pmg
  • 106,608
  • 13
  • 126
  • 198
  • Please bear with me if question is absurd. Incase implementation didn't happen in a sequence, why does it give same response everytime i run the program? Doesn't it mean there's actually some sequence followed? – Gayathri Nov 01 '19 at 10:25
  • See https://ideone.com/avSVxI -- does not compile. The "sequence" you see is bad luck. It might change when there's a full moon, when you compile again, when your teacher is watching ... and it may even do something else entirely, like printing the lyrics of the national anthem of Spain :) – pmg Nov 01 '19 at 10:32
  • What's WHICHx in that? it's neither declared nor initialized. On a fun note, "An astrologer here, say more about my future please?" :-) – Gayathri Nov 01 '19 at 10:37
  • I have no idea which `WHICHx` happens when you run the program (but reverse engineering might tell you what happened); it's Undefined Behaviour. That was just an attempt at explaining the behaviour you see, not the behaviour of the code in general. – pmg Nov 01 '19 at 10:44
  • I appreciate your effort on that . – Gayathri Nov 01 '19 at 10:50
1

This is standard undefined behaviour, order of evalution of function arguments is non deterministic. Read [Why are these constructs using pre and post-increment undefined behavior?

moghya
  • 854
  • 9
  • 18
  • If you find a duplicate, please flag it as a duplicate instead of linking the dup in an answer. – klutt Nov 01 '19 at 09:03