简体   繁体   English

为什么该程序按其方式运行?

[英]Why does this program run the way it does?

#include<stdio.h>
int main()
{
    int a[5] = {5, 1, 15, 20, 25};
    int x, y, z;
    x = ++a[1];
    y = a[1]++;
    z = a[x++];
    printf("%d, %d, %d", x, y, z);
    return 0;
 }

"x" is printed as 3, but I would have expected it to return 2? “ x”打印为3,但我希望它返回2? In fact if I remove the "++" and set x equal to a[1], it returns as 2. It adds 1 to any value that is actually there. 实际上,如果我删除“ ++”并将x设置为等于a [1],则它将返回为2。它将1加到实际存在的任何值上。 Am I missing something? 我想念什么吗?

"x" is printed as 3, but I would have expected it to return 2? “ x”打印为3,但我希望它返回2?

 x = ++a[1]; 

Here x = 2 because of pre-increment 由于预先增加,此处x = 2

The you have 你有

z = a[x++];

x ++ = x + 1 = 2+1 = 3

Hence x=3 因此x=3

x = ++a[1];//Increment a[1] and then assign it to x
y = a[1]++;//assign a[1] to y and then increment a[1]
z = a[x++];//assign a[2] to z and then increment x

The ++ is called an increment operator. ++称为增量运算符。 It increases the value by 1. In you code you have 它会将值增加1。在您的代码中,您有

x = ++a[1];

++ before a variable is the Pre Increment Operator . 变量之前的++预增量运算符 It increments the value of a[1] before assigning it to x . 它将a[1]的值递增,然后将其分配给x So the value of a[1] and x becomes 3. 因此, a[1]x变为3。

The other one 另一个

y = a[1]++;

++ after the variable is the Post Increment Operator . 变量后的++后增量运算符 It assigns a[1] ( which has already become 3 ) to y and then increments the value of a[1] to 4. 它将a[1] (已经变成3)分配给y ,然后将a[1]的值递增到4。

This link will help you 此链接将为您提供帮助

http://www.c4learn.com/c-programming/c-increment-operator/#A_Pre_Increment_Operator http://www.c4learn.com/c-programming/c-increment-operator/#A_Pre_Increment_Operator

x=++a[1]; //  Now x got the value 2. 

In this line, 在这一行,

z = a[x++]; // x++ will be happen after the assigning of a[2] to z. So the value of x is incremented. So the x value is became 3. 

It is post increment so the z got the value as 15. Refer this link . 它是后增量,因此z的值为15。请参阅此链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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