[英]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 我不明白的是我如何得到的价值
i
作为3
It should be 2 right? 应该是2对吧?
Or is it related with C compiler's right to left evaluation of printf()
statement? 还是与C编译器从右到左评估
printf()
语句有关?
m = a[i++]
行第二次将i
从2递增到3。
What is a[1]
? 什么是
a[1]
? It's 1. What's is ++a[1]
? 是1.什么是
++a[1]
? It's 2. i
is now 2, so far so good. 现在是2。
i
现在是2,到目前为止一切都很好。
But when you calculate m
, you have a[i++];
但是,当您计算
m
,您有a[i++];
, i
now is 3 (Note that m
will be a[2]
- i
increments after the evaluation). ,
i
现在是3(请注意, m
将为a[2]
i
在求值后递增)。
i = ++a[1];
Pre-increment operator. 预递增运算符。
a[1]
becomes 2, then i
becomes 2; a[1]
变为2,然后i
变为2;
j = a[1]++;
Post-incement operator. 增后运算符。
j
becomes 2, then a[1]
becomes 3. j
变成2,然后a[1]
变成3。
m = a[i++];
Post-increment operator. 后增量运算符。
m
becomes a[2]
= 15, then i
becomes 3. m
变成a[2]
= 15,然后i
变成3。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.