2

I can't understand how this works and why it produces the following output.

int main()
{
    int i=0;
    int a=5;
    int x=0;

    for(i=0; i<5; x=(i++,a++))
    {
        printf("i=%d a=%d x=%d\n",i,a,x);
    }
}

this give as output:

i=0 a=5 x=0
i=1 a=6 x=5
i=2 a=7 x=6
i=3 a=8 x=7
i=4 a=9 x=8
4

5 回答 5

3

暂时忘记这些++,它们只是分散注意力。

int a = 5;
int i = 0;    
int x = (i, a);

将 的值设置x为 5。i被评估并丢弃,然后a被评估并分配给x

在你的循环中,后增量a++做它一直做的事情;返回当前值,然后递增变量。所以在增加之前x取 的值a,然后a' 的值增加 1。因为i++也被评估了,所以它的值也增加了。

于 2014-07-25T14:00:45.103 回答
1

考虑您的示例和输出(除了我将初始值x设为 22):

int i=0;
int a=5;
int x=22;

for(i=0; i<5; x=(i++,a++))
{
    printf("i=%d a=%d x=%d\n",i,a,x);
}

印刷:

i=0 a=5 x=22
i=1 a=6 x=5
i=2 a=7 x=6
i=3 a=8 x=7
i=4 a=9 x=8

请注意,x在循环之前具有 x 的初始值,或者在循环的最后一次行程中具有先前的值。

回想一下,任何for循环都可以表示为等价while循环。

for循环:

for(exp 1; exp 2; exp 3){
    expressions
}

相当于:

exp 1;
while(exp 2){
   expressions
   exp 3;
}

所以你的for循环可以写成:

int i=0;              // exp 1 from the for loop
int a=5;
int x=22;

while(i<5){           // exp 2
    // loop body
    printf("i=%d a=%d x=%d\n",i,a,x);

    x=(i++,a++);      // exp 3 from the for loop
}

打印相同的输出。

在循环结束时评估的事实exp 3(无论是 for 还是 while 循环)就是为什么x在循环体中有 x 的先前值。

最后要考虑的是逗号运算符。表达方式:

i=(a+=2, a+b)
   ^^^               evaluate a then add 2
       ^             comma operator in this case
          ^^         add b to a

 ^                   store the final expression -- the RH of the comma operator -- 
                     into i
于 2014-07-25T14:39:56.587 回答
1

逗号操作符的意思是:全部执行,并返回最后一个值;

例子:

A = (b+=1,c+2,d+1);

这句话将b加1,c加2(但不会修改),d加1。因此 d+1 是最后一个表达式 A 将被设置为其值。

post 和 pre 运算符 ++ 很棘手。

A++ 的意思是:返回 A 的值,然后递增它。++A 意思是:增加 A 然后返回它的值。

所以如果 A=2

b=A++; // set b to 2 and increments A one unity
b=++A; // increments A to 4 and sets b to 4
于 2014-07-25T14:12:58.797 回答
1

我想你理解这样的 for 循环:

for(i=0; i<5; i++)

您可能还想增加两个变量;如果你用逗号分隔它们;像这样:

for(i=0; i<5; i++,a++)

在每个循环开始时,两者都ia递增。现在只x=(i++,a++)需要解释表达式: x获取分配的两个值中的最后一个。和写法一样:

x=i++;
x=a++;

当然 a 是后递增的,因此首先将其值分配给 x;只有这样 a 才会增加。

于 2014-07-25T14:01:57.890 回答
1

很简单,您使用的两个运算符都是“后增量”,这意味着首先会发生赋值,然后会发生变量的增量。让我们通过一个例子来理解,假设,

i=5
x=i++;
printf("%d", x)

上面的代码将输出为5

i=5
x=++i;
printf("%d", x)

这将输出为6

希望你明白其中的逻辑。

于 2014-07-25T14:04:03.130 回答