简体   繁体   中英

Why does i print a value of 3 in the following code?

The outut of the code below is: 3 2 15
I was expecting 2 2 15
Why is this?

#include <stdio.h>

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

The increment/decrement operators actually change the value of the object, not just return the resulting value. In the line m=a[i++]; you are incrementing i again.

becuase you increment it twice:

i=++a[1];     // i = 2
j=a[1]++;
m=a[i++];     // i = 3
printf("%d %d %d",i,j,m);

I want it to help you.

#include<stdio.h>
int main()
{
int a[5]={5,1,15,20,25};
i=++a[1]; // i = 2
j=a[1]++; // j = 2
m=a[i++]; // m = 15, i = 3
printf("%d %d %d",i,j,m);
return 0;
}

Code

#include <stdio.h>

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

Lets go through this step by step..

  • a[1] is 1

  • i is ++1 that is.... 2

  • m is a[i] that is a[2] which is... 15

After this statement i++ is executed, so

after m = 15,

i becomes 3,

These values are printed using printf

Lets proceed step by step:

#include <stdio.h>

int main() {
    int a[5] = { 5, 1, 15, 20, 25 };
    i = ++a[1];  // a[1] is incremented, becomes 2, i gets this value 2
    j = a[1]++;  // j gets a[1] which is 2, then a[1] is incremented and becomes 3
    m = a[i++];  // m gets a[2] which is 15, i is incremented and becomes 3
    printf("%d %d %d", i, j, m);  // prints 3 2 15
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM