1

This is a sample code I have from someone and it runs giving the answers

3, 2, 15

Can someone please explain how this piece of code works and how it got to those outputs?

Code:

int a[5] = { 5, 1, 15, 20, 25 };
int i, j, m;
i = ++a[1];
j = a[1]++;
m = a[i++];
printf("%d, %d, %d", i, j, m);
_getch();
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
SSG
  • 21
  • 4

3 Answers3

7

You should know about pre-increment (++var) and post-increment (var++).

Let's break down the code line by line, shall we?

  1. i = ++a[1]; Here, a[1] is 1, (2nd element of array a), is pre-incremented to 2 and that value is stored into i.

  2. j = a[1]++; same, the 2 is stored into j and then a[1] is post-incremented to the value 3.

  3. m = a[i++]; a[2], i.e., 15 is stored into m, and i is post-incremented to 3.

  4. printf("%d, %d, %d", i, j, m); -- Surprise!!

lurker
  • 56,987
  • 9
  • 69
  • 103
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

Exactly so:

  • **Pre- ** Increment: increment the value in the variable, then use the incremented value.

  • ** Post- ** Increment: grab the value and use it. After grabbing the not-yet-incremented value, increment the value that's stored in the variable. Proceed, using the value as it was before.

"Operator precedence" rules mean that, for example, ++a[1] means that the meaning of a[1] will be resolved first, then the ++ operator will be applied to that memory-location. The value of the number-one element (which is actually the second element ...) will be incremented, and the incremented value will be returned for use by the statement.

Mike Robinson
  • 8,490
  • 5
  • 28
  • 41
-1
  1. a[1] refers to the second element which is 1
  2. In the step i=++a[1],a[1] is incremented to 2 and assigned to i
  3. in the next step a[1] is incremented again and the value of a[1] is incremented again to 3
  4. in the third step,m=a[i++], value of i is 2 from step 1 , but it is a post increment .so, m will remain m=a[2]
mch
  • 9,424
  • 2
  • 28
  • 42