简体   繁体   中英

What is logic behind the output of following code?

I executed following piece of code:

int a[] = {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);

and I got output as follow :-

3 2 15

The part which I don't understand is how I got value of i as 3

It should be 2 right?

Or is it related with C compiler's right to left evaluation of printf() statement?

m = a[i++]行第二次将i从2递增到3。

What is a[1] ? It's 1. What's is ++a[1] ? It's 2. i is now 2, so far so good.

But when you calculate m , you have a[i++]; , i now is 3 (Note that m will be a[2] - i increments after the evaluation).

i = ++a[1];

Pre-increment operator. a[1] becomes 2, then i becomes 2;

j = a[1]++;

Post-incement operator. j becomes 2, then a[1] becomes 3.

m = a[i++];

Post-increment operator. m becomes a[2] = 15, then i becomes 3.

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