The name of a variable, its identifier, can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upperand lowercase letters are distinct: Identifiers in C++(www.cppentry.com) are case-sensitive. The following defines four distinct identifiers:
-
- int somename, someName, SomeName, SOMENAME;
There is no language-imposed limit on the permissible length of a name, but out of consideration for others that will read and/or modify our code, it should not be too long.
For example,
gosh_this_is_an_impossibly_long_name_to_type
is a really bad identifier name.
这是标识符的语法规则。变量名、函数名、类名等都是标识符。注意,有些标识符是系统保留的,我们应该避免在程序中使用,包括以下画线开头,或者包含两个下画线的标识符等。见so228783。
在代码中给变量和函数命名是一项关键的任务,可参考《代码大全》有关章节。C++(www.cppentry.com) 程序应该遵循统一的命名格式,例如对函数和类型命名LikeThis,对局部变量命名likeThis,对成员变量命名likeThis_,对预处理宏命名LIKE_THIS。
C++(www.cppentry.com) Keywords
C++(www.cppentry.com) reserves a set of words for use within the language as keywords. Keywords may not be used as program identifiers. Table 2.2 on the next page lists the complete set of C++(www.cppentry.com) keywords.
C++(www.cppentry.com) also reserves a number of words that can be used as alternative names for various operators. These alternative names are provided to support character sets
that do not support the standard set of C++(www.cppentry.com) operator symbols. These names, listed in Table 2.3, also may not be used as identifiers:
In addition to the keywords, the standard also reserves a set of identifiers for use in the library. Identifiers cannot contain two consecutive underscores, nor can an identifier begin with an underscore followed immediately by an upper-case letter. Certain identifiers—those that are defined outside a function—may not begin with an underscore.
Conventions for Variable Names
There are a number of generally accepted conventions for naming variables. Following these conventions can improve the readability of a program.
· A variable name is normally written in lowercase letters. For example, one writes index, not Index or INDEX.
· An identifier is given a mnemonic name—that is, a name that gives some indication of its use in a program, such as on_loan or salary.
· An identifier containing multiple words is written either with an underscore between each word or by capitalizing the first letter of each embeddedword. For example, one generally writes student_loan or studentLoan, not studentloan.
The most important aspect of a naming convention is that it be applied consistently.
EXERCISES SECTION 2.3.2
Exercise 2.14: Which, if any, of the following names are invalid Correct each identified invalid name.
(a) int double = 3.14159; (b) char _;
(c) bool catch-22; (d) char 1_or_2 = ’1’;
(e) float Float = 3.14f;