`char _3 = 'c'` 在 C 和 C++ 中有效吗?

Is `char _3 = 'c'` valid in C and C++?

考虑到,我已将变量名称声明为带下划线的数字。

#include <stdio.h>

int main()
{
   char _3 = 'c';
   printf("%c\n",_3);
}

我想知道,它在 C 和 C++ 中运行良好。那么,它有效吗?

所有变量名必须以字母或字母开头 下划线。所以是的,它是有效的,除非你将它放在文件范围内。 (注意双下划线,它是为编译器内部使用保留的)

但是,我不建议使用这样名称的变量,因为它可能会使 reader.

混淆

来自 C++ 2003 标准:

17.4.3.1.2 Global names [lib.global.names]

Certain sets of names and function signatures are always reserved to the implementation:

  • Each name that contains a double underscore (_ _) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use.
  • Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.165

165) Such names are also reserved in namespace ::std (17.4.3.1).

除全局范围外的任何范围都有效1.

C++17 - n4659 / [lex.name]

In addition, some identifiers are reserved for use by C++ implementations and shall not be used otherwise; no diagnostic is required.

  • Each identifier that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

标准库实际上在命名空间范围内有一个示例,继承自 booststd::bind 的占位符。

而 C 有类似的措辞:

C11 - n1570 / 7.1.3 Reserved identifiers

Each header declares or defines all identifiers listed in its associated subclause, and optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.

  • All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.

虽然范围的选择更加有限。


1 - 不是规范术语,只是两个标准使用的术语的混合。