-1

I felt that such an expression should be invalid but I was able to compile it and got the answer 5. At the end I felt that even if it does answer should be 4 not 5.

int main(void)
{
  int i=1;

  // how is the next line evaluated ie in what sequence??

  i=2+2*i++;
  printf("%d",i);
  return 0;
}

The output I got was 5. I can not understand how it should give the value.

Casey
  • 41,449
  • 7
  • 95
  • 125
chinmay
  • 850
  • 2
  • 8
  • 16

1 Answers1

4

This is undefined behaviour, since i is modified more than once between sequence points. For instance, this compiler gives 4 as the answer, because it puts the increment after the assignment. Another reasonable answer is 6, if the increment is before the assignment. But, as you've found, the compiler is permitted to make the answer whatever it wants, including 5.

See here for more about sequence points and undefined behaviour.

Community
  • 1
  • 1
1''
  • 26,823
  • 32
  • 143
  • 200