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

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

问题描述

答案了解未定义行为和顺序点之后,我写了一个小程序:

 的#include<&stdio.h中GT;诠释主要(无效){
  INT I = 5;
  I =(I,+ +我,1)+ 1;
  的printf(%d个\\ N,I);
  返回0;
}

输出为 2 。哦,上帝,我没有看到减量来了!这里发生了什么?

此外,在编译上面的code,我得到了一个警告说:


  

px.c:5:8:警告:逗号前pression的左手操作数的结果。

无影响

  [-Wunused-值1 =(我,我+ 1)+ 1;
                        ^


为什么呢?但也许它会自动通过我的第一个问题的答案回答。


解决方案

在除权pression (I,+ +我,1),用逗号是逗号操作


  

逗号(再由令牌 psented $ P $)是评估其第一个操作数和丢弃的结果,然后一个二进制运算符将第二个操作数并返回该值(和类型)。


由于它放弃其第一个操作数,所以一般的其中第一个操作数的唯一有用的可取副作用。如果副作用第一个操作数不发生,则编译器可能会产生约有没有影响前pression警告。

所以,在上述前pression,最左边的 I 进行评估,其价值将被丢弃。然后 ++我进行评估,并会增加 I 1次的前pression的价值 ++我将被丢弃,的但副作用 I 是永久的的。然后 1 将被评估和前pression的值将是 1

这是等同于

 我; //我评估和丢弃它的价值。本没有影响。
++我; //我评估,并加1,并丢弃前pression价值++我
I = 1 + 1;

注意上述前pression是完全有效的,不会调用未定义行为,因为有一个的序点

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;
}

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: 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.

解决方案

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.

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.

It is equivalent to

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,+ +我,1)+ 1;做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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