main 结束时 y 的值是多少?
const int x = 5;
int main(int argc, char** argv)
{
int x[x];
int y = sizeof(x) / sizeof(int);
return 0;
}
y is 5
main结束时局部变量x的值是多少?
int x = 5;
int main(int argc, char** argv)
{
int x = x;
return 0;
}
x is undefined
最佳答案
声明时
int x[x];
全局x
用于定义数组的大小。 []
中的x
是全局变量,因为局部变量的声明还没有完成。
在第二种情况下,
int x = x;
是未定义的行为,因为 RHS 上的 x
与 LHS 上的 x
相同,因为 x
的声明是通过以下方式完成的遇到 RHS 上的时间 x
。
这些在 C++11 标准中有描述:
3.3.2 Point of declaration
1 The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any), except as noted below. [ Example:
int x = 12;
{ int x = x; }Here the second x is initialized with its own (indeterminate) value. — end example ]
2 Note: a name from an outer scope remains visible up to the point of declaration of the name that hides it.[ Example:
const int i = 2; { int i[i]; }
declares a block-scope array of two integers. — end example ] — end note ]
关于c++ - 局部变量如何隐藏全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42743884/