简体   繁体   English

变量和常量同名

[英]Variable and constant with same name

I have a C code snippet as follows: 我有一个C代码片段如下:

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

The code snippet would be compiled and run correctly. 代码片段将被编译并正确运行。 But I don't understand how to differentiate x 'variable' and x 'const'. 但我不明白如何区分x'变量'和x'常量'。

For C++ this is covered in the draft C++ standard section 3.3.2 Point of declaration : 对于C ++中,这是包括在草案C ++标准3.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. 声明的声明就在其完整的声明者(第8条)之后和初始化者(如果有的话)之前,除非如下所述。 [ Example: [例如:

 int x = 12; { int x = x; } 

Here the second x is initialized with its own (indeterminate) value. 这里第二个x用它自己的(不确定的)值初始化。 —end example ] - 末端的例子]

and: 和:

[ 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 ] - 末端示例] - 尾注]

So in your case: 所以在你的情况下:

int x[x];

The const int x is visible until the closing ] . const int的 x可见直至收盘] To refer to const int x after that point you can use a qualified identifer : 要在该点之后引用const int x ,您可以使用限定标识符

::x

Of course this begs the question, why not just use different names and not have to deal with these edge cases? 当然这引出了一个问题,为什么不只是使用不同的名称而不必处理这些边缘情况?

C C

The equivalent quotes form the draft C99 standard would be from section 6.2.1 Scopes of identifiers ( emphasis mine ): C99标准草案中的等效引号将来自第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. 任何其他标识符的范围都在其声明者完成之后开始。

and: 和:

[...] 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. 在外部作用域中声明的实体在内部作用域内是隐藏的(并且不可见)。

there is no way to make the x in the outer scope visible in C. 没有办法使外部范围中的x在C中可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM