2.2.3 标识符
C++(www.cppentry.com)的标识符(identifier)由字母、数字和下画线组成,其中必须以字母或下画线开头。标识符的长度没有限制,但是对大小写字母敏感:
- // 定义4个不同的int变量
- int somename, someName, SomeName, SOMENAME;
如表2.3和表2.4所示,C++(www.cppentry.com)语言保留了一些名字供语言本身使用,这些名字不能被用作标识符。
同时,C++(www.cppentry.com)也为标准库保留了一些名字。用户自定义的标识符中不能连续出现两个下画线,也不能以下画线紧连大写字母开头。此外,定义在函数体外的标识符不能以下画线开头。
变量命名规范
变量命名有许多约定俗成的规范,下面的这些规范能有效提高程序的可读性:
标识符要能体现实际含义。
变量名一般用小写字母,如index,不要使用Index或INDEX。
用户自定义的类名一般以大写字母开头,如Sales_item。
如果标识符由多个单词组成,则单词间应有明显区分,如student_loan或studentLoan,不要使用studentloan。
对于命名规范来说,若能坚持,必将有效。
表2.3:C++(www.cppentry.com)关键字
|
表2.3:C++(www.cppentry.com)关键字
|
|
alignas continue friend register true
alignof decltype goto reinterpret_cast try
asm default if return typedef
auto delete inline short typeid
bool do int signed typename
break double long sizeof union
case dynamic_cast mutable static unsigned
catch else namespace static_assert using
char enum new static_cast virtual
char16_t explicit noexcept struct void
char32_t export nullptr switch volatile
class extern operator template wchar_t
const false private this while
constexpr float protected thread_local
const_cast for public throw
|
|
表2.4:C++(www.cppentry.com)操作符替代名
|
|
and bitand compl not_eq or_eq xor_eq
and_eq bitor not or xor
|
2.2.3节练习
练习2.12:请指出下面的名字中哪些是非法的?
(a) int double = 3.14; (b) int _;
(c) int catch-22; (d) int 1_or_2 = 1;
(e) double Double = 3.14;