i=i++ 的输出差异+ ++c;和 i=++i + c++;
我不知道这是否是特定于编译器的,但是当我尝试在 DevC++ 中运行两个表达式
时 i=c=b=0;
i=i++ + ++c
给出 2
而 i=++i + c++
给出 1
但是 b=i++ + ++c
和 b=++i + ++c
为两个表达式生成结果 1
。
我确实知道根据 C 标准规范,在同一表达式中将变量递增两次会导致未定义的值,但我很好奇编译器如何生成这些输出。有人可以解释一下如何以及为什么吗?
I don't know if this is compiler specific but when I tried running the two expressions in DevC++
When i=c=b=0;
i=i++ + ++c
gives 2
whereas i=++i + c++
gives 1
Butb=i++ + ++c
andb=++i + ++c
produces the result 1
for both expressions.
I do know that incrementing a variable twice in the same expression results in an undefined value according to the C standard specification but I'm curious how the compiler produces these output. Could someone please explain how and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
i++ + ++c
,c
递增(到 1),然后0 + 1
存储在i
,最后i
递增,得到2
。++i + c++
,i
递增(到 1),然后1 + 0
存储在i
,然后c
递增。这就是我理解编译器所做的事情的方式,但正如其他人所说,不要指望其他地方的这种行为。
i++ + ++c
, thec
is incremented (to 1), then0 + 1
is stored ini
, and finallyi
is incremented, giving2
.++i + c++
, thei
is incremented (to 1), then1 + 0
is stored ini
, thenc
is incremented.That's how I would understand what the compiler did, but as everyone else is saying, don't count on this behavior elsewhere.
你确定 b = ++i + ++c = 1 吗?或者是 b = ++i + c++ ?这是我对你的问题的解释。
Are you sure b = ++i + ++c = 1? or was it b = ++i + c++? Here is my explanation of your question.
i++
和++i
完全不同,i++
是后增量,意味着在表达式中计算i
然后一旦评估就增加。++i
表示先递增然后计算表达式。我在您的示例中看到您设置了
i = ++i/i++
,这是评论中提到的未定义行为。i++
and++i
are completely different,i++
is post increment which means evaluatei
in the expression and then increment once its evaluated.++i
means increment then evaluate the expression.I see in your example you set
i = ++i/i++
, this is undefined behavior as mentioned in a comment.C99 标准明确指出(6.5,p2)
表达式
i = ++i;
和i = i++;
都更新i
两次,这是不允许的。The C99 standard says explicitly (6.5, p2)
The expressions
i = ++i;
andi = i++;
both updatei
twice, which is not allowed.