c++ - 局部变量如何隐藏全局变量

标签 c++ c++11

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/

相关文章:

c++ - "Access violation"与 COleVariant

c++ - CMake add_compile_options 在适当的时候会影响链接器选项吗?

c++ - 范围最小值/最大值查询

c++ - 为什么 C++ 允许将 std::initializer_list 强制转换为基本类型,并用于初始化它们?

C++11计时:assigning values to time_point objects

c++ - Armadillo 相当于 A(find(A<0)) = 0

c++ - switch 语句条件下同时具有模板和非模板转换运算符的类

c++ - 使用 Qt/C++ 的排序算法 - 对结构的 QList 进行排序

c++ - 计算中常用值的预定义 - 它会改变什么吗?

c++ - 将继承的参数传递给基类构造函数,然后在派生类构造函数中做一些事情