gpt4 book ai didi

c++ - 同名变量和常量

转载 作者:太空狗 更新时间:2023-10-29 23:44:30 25 4
gpt4 key购买 nike

我有一个 C 代码片段如下:

const int x = 5;
void main()
{
int x[x];
int y = sizeof(x) / sizeof(int);
printf("%d",y);
}

代码片段将被编译并正确运行。但我不明白如何区分 x 'variable' 和 x 'const'。

最佳答案

对于 C++,这包含在 draft C++ standard3.3.2 部分声明点:

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 ]

和:

[ 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 ]

所以在你的情况下:

int x[x];

const int x 在结束 ] 之前是可见的。要在那之后引用 const int x,您可以使用 qualified identifer :

::x

当然这引出了一个问题,为什么不使用不同的名称而不必处理这些边缘情况呢?

C

等效引号构成 draft C99 standard将来自 6.2.1 标识符范围(强调我的):

Structure, union, and enumeration tags have scope that begins just after the appearance of the tag in a type specifier that declares the tag. Each enumeration constant has scope that begins just after the appearance of its defining enumerator in an enumerator list. Any other identifier has scope that begins just after the completion of its declarator.

和:

[...] Within the inner scope, the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope.

没有办法使外部作用域中的 x 在 C 中可见。

关于c++ - 同名变量和常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29130530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com