What’s Next 781
21
- Use whitespace to help readability.
- Don’t use spaces between object and array names and their operators (.,->,[]).
- Unary operators are associated with their operands, so don’t put a space between
them. Do put a space on the side away from the operand. Unary operators include
!,~,++,--,-,*(for pointers),&(casts), and sizeof. - Binary operators should have spaces on both sides:+,=,*,/,%,>>,<<,<,>,==,!=,
&,|,&&,||,?:,=,+=, and so on. - Don’t use lack of spaces to indicate precedence:
(4+ 3*2). - Put a space after commas and semicolons, not before.
- Parentheses should not have spaces on either side.
- Keywords, such as if, should be set off by a space:if (a == b).
- The body of a single-line comment should be set off from the //with a space.
- Place the pointer or reference indicator next to the type name, not the variable
name:
char foo;
int& theInt;
rather than
char foo;
int &theInt; - Do not declare more than one variable on the same line.
Naming Identifiers ..........................................................................................
The following are guidelines for working with identifier names:
- Identifier names should be long enough to be descriptive.
- Avoid cryptic abbreviations.
- Take the time and energy to spell things out.
- Do not use Hungarian notation. C++ is strongly typed and there is no reason to put
the type into the variable name. With user-defined types (classes), Hungarian nota-
tion quickly breaks down. The exceptions to this might be to use a prefix for point-
ers (p) and references (r), as well as for class member variables (its). - Short names (i, p, x, and so on) should be used only where their brevity makes the
code more readable and where the usage is so obvious that a descriptive name is
not needed. In general, however, you should avoid this. Also, avoid the use of the
letters i, l, and o as variable names because they are easy to confuse with numbers.