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();
4
  • 1
    Get what output? And what output did you expect? Commented May 28, 2015 at 12:05
  • 1
    Also, this operator precedence table might help you understand it a little. Commented May 28, 2015 at 12:06
  • @JoachimPileborg, his output is in the second line of the post 3, 2, 15. He doesn't expect output, he would like to understand where it came from. Commented May 28, 2015 at 12:21
  • @user1717828 The output wasn't clear in the original post before the edit, and I'm sure the OP expected something. Commented May 28, 2015 at 12:28

3 Answers 3

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!!

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

-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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.