问题描述
以下代码可以通过g ++和Visual C ++进行编译。为什么是合法的?它看起来不合理,并可能导致隐藏的错误。
The following code can pass compiling under both g++ and Visual C++. Why is it legal? It looks unreasonable, and may cause hidden bugs.
int main() {
int i = i;
}
推荐答案
/ strong> 语法合法,但如果使用 x
,则会导致未定义的行为。
It's syntactically legal, but results in undefined behavior if you use x
.
这是不合法,因为您正在为一个未初始化的变量分配另一个(好,相同)未初始化的变量。只是因为它的编译并不意味着它是合法的。它是有效的C ++语法,是的,但不合法。
It's not legal because you're assigning an uninitialized variable with another (well, the same) uninitialized variable. Just because it compiles doesn't mean it's legal. It's valid C++ syntax, yes, but not legal.
赋值运算符的右边必须在赋值时进行完全求值。在这种情况下,这是 i
,这是没有初始化。
The right hand side of the assignment operator must be fully evaluated at the time of the assignment. In this case, that's i
, which isn't initialized.
对Steve Jessop的点数:
Credits to Steve Jessop, who dug up the quote:
到价值转换
这篇关于为什么是'int i = i;'法律?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!