-1

Could someone please tell me step by step how this goes through? I'm having trouble understanding how x++ works. I understand that the x++ keeps the original value then increments it, but in this case it what does it do? Shouldn't it go up by 1 two times?

int main()
{
    int y, x=3;
    x=x++ +1;
    y=++x;
    printf ("x=%d y=%d",x,y);

    return 0;
}
synth
  • 65
  • 4

1 Answers1

0

The line x = x+++1; is being parsed as x = (x++) + 1;. This in theory would mean "Add 1 to the current value of x, then assign the result to x, then increment x". However, as Eugene Sh. mentioned, this is undefined behavior in C, which means that any code that relies on this behavior is not portable and may behave differently on different systems.

Here is a clarifying example. The line x = y++ is interpreted as x = y; y = y + 1;

int main() {                                                                                         
  int x = 0;                                                                                         
  int y = 0;                                                                                         
  x = y++;                                                                                           
  printf("%d\n%d\n", x, y);                                                                          
                                                                                                     
  return 0;                                                                                          
}   
> 0
> 1

To be clear, the reason your code is undefined is because x is being assigned to an expression containing x++. Writing y = x+++1 is perfectly defined, and is equivalent to

y = x + 1;
x = x + 1;
squidwardsface
  • 389
  • 1
  • 7