i =(i,++ i,1)+ 1;做? [英] What does i = (i, ++i, 1) + 1; do?

查看:174
本文介绍了i =(i,++ i,1)+ 1;做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读关于未定义行为和序列点的此答案后,我写了一个小程序:

After reading this answer about undefined behavior and sequence points, I wrote a small program:

#include <stdio.h>

int main(void) {
  int i = 5;
  i = (i, ++i, 1) + 1;
  printf("%d\n", i);
  return 0;
}

输出是 2 。哦,天啊,我看不到减量来了!这里发生了什么?

The output is 2. Oh God, I didn't see the decrement coming! What is happening here?

另外,在编译上述代码时,我收到一条警告:

Also, while compiling the above code, I got a warning saying:


px.c:5:8:警告:逗号表达式的左侧操作数没有影响

px.c:5:8: warning: left-hand operand of comma expression has no effect

  [-Wunused-value]   i = (i, ++i, 1) + 1;
                        ^


为什么?但是可能会由我的第一个问题的答案自动回答。

Why? But probably it will be automatically answered by the answer of my first question.

推荐答案

在表达式 i,++ i,1),使用的逗号是逗号操作符

In the expression (i, ++i, 1), the comma used is the comma operator


逗号运算符(由令牌表示,)是一个二进制运算符,它评估其第一个操作数并丢弃结果,然后评估第二个操作数并返回此值(并键入)。

the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

因为它丢弃了第一个操作数,所以它通常只有在第一个操作数具有希望的副作用 。如果没有发生对第一个操作数的副作用,则编译器可能会生成关于表达式的警告,而不起作用。

Because it discards its first operand, it is generally only useful where the first operand has desirable side effects. If the side effect to the first operand does not takes place, then the compiler may generate warning about the expression with no effect.

所以,在上面的表达式中,最左边的 i 将被评估,其值将被丢弃。然后 ++ i 将被评估,并将 i 加1,再次表达式 ++ i 将被丢弃,但副作用 i 是永久的。然后 1 将被评估,表达式的值将为 1

So, in the above expression, the leftmost i will be evaluated and its value will be discarded. Then ++i will be evaluated and will increment i by 1 and again the value of the expression ++i will be discarded, but the side effect to i is permanent. Then 1 will be evaluated and the value of the expression will be 1.

相当于

i;          // Evaluate i and discard its value. This has no effect.
++i;        // Evaluate i and increment it by 1 and discard the value of expression ++i
i = 1 + 1;  

请注意,上述表达式是完全有效的,不会调用未定义的行为因为在逗号运算符的左右操作数的评估之间存在序列点

Note that the above expression is perfectly valid and does not invoke undefined behavior because there is a sequence point between the evaluation of the left and right operands of the comma operator.

这篇关于i =(i,++ i,1)+ 1;做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆