Is `char _3 = 'c'` valid in C and C++?
考虑到,我已经声明变量名为带下划线的数字。
1 2 3 4 5 6 7 8 | #include <stdio.h> int main() { char _3 = 'c'; printf("%c ",_3); } |
我想知道,它在C和C++中工作得很好。那么,这是有效的吗?
所有变量名必须以字母表或强调。所以是的,它是有效的,除非您将它放在文件范围内。(但请注意双下划线,它是为编译器内部使用而保留的)
不过,我不建议使用这样的变量名,因为它可能会让读者感到困惑。
从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—N465 9/[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.
标准库实际上在名称空间范围内有一个示例,它继承自
C有相似的措词:
C11-N1570/7.1.3保留标识符
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.
尽管范围的选择更加有限。