logoalt Hacker News

vcdkyesterday at 9:28 PM1 replyview on HN

Well... tried it on macOS using vanilla gcc, the results surprised me:

  $ /bin/cat x.c; gcc -w -o x x.c; ./x
  #include <stdio.h>
  
  int main()
  {
      int a = 5;
      a += a++ + a++;
      printf("a = %d\n", a);
  }
  a = 18
Not what I expected. This must be how it works:

- The first a++ expression results in 5, after a = 6 - The second a++ expression results in 6, after a = 7 - Only then the LHS a is evaluated for the addition-assignment, so we get: a = 7 + 5 + 6 = 18


Replies

rmu09yesterday at 9:45 PM

the original question has a=, you have a+=

show 1 reply