i = ++ i + ++ i;在C ++中 [英] i = ++i + ++i; in C++
问题描述
有人可以向我解释为什么此代码显示14吗?另一个学生只是问我,无法解决.
Can someone explain to me why this code prints 14? I was just asked by another student and couldn't figure it out.
int i = 5;
i = ++i + ++i;
cout<<i;
推荐答案
副作用在C ++中未定义.此外,在单个表达式中两次修改变量没有定义的行为(请参见 C ++标准,第5.0.4节,物理第87页/逻辑第73页).
The order of side effects is undefined in C++. Additionally, modifying a variable twice in a single expression has no defined behavior (See the C++ standard, §5.0.4, physical page 87 / logical page 73).
解决方案:不要在复杂的表达中使用副作用,在简单的表达中不要使用多个副作用.启用编译器可以给您的所有警告也没有什么坏处:在命令行中添加-Wall
(gcc)或/Wall /W4
(Visual C ++)会产生合适的警告:
Solution: Don't use side effects in complex expression, don't use more than one in simple ones. And it does not hurt to enable all the warnings the compiler can give you: Adding -Wall
(gcc) or /Wall /W4
(Visual C++) to the command line yields a fitting warning:
test-so-side-effects.c: In function 'main':
test-so-side-effects.c:5: warning: operation on 'i' may be undefined
test-so-side-effects.c:5: warning: operation on 'i' may be undefined
很明显,代码编译为:
i = i + 1;
i = i + 1;
i = i + i;
这篇关于i = ++ i + ++ i;在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!