0

I have this code:

#include <stdio.h>

int main(){
   int a[5] = {5, 1, 15, 20, 25};
   int i, j, k = 1, m;
   i = ++a[1];
   j = a[1]++;
   m = a[i++];
   printf("\n%d %d %d", i, j, m);

   return 0;
}

The output is: 3 2 15.
Why is that? Shouldn't ++a[1] be 2, a[1]++ is 2, and a[i++] should be 20 because it's a at index 3?
So why is the output not 2 2 20.

Thanks!

1 Answers1

1

When a[i++] is evaluated, i has the value of 2. So the value of this expression is the same as a[2], which is 15. The side effect of this expression is a post-increment of i; this side effect will increment i to the value of 3 and takes effect after the expression-value of 15 got evaluated.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58