What’s Next 779
21
Programming Style ..............................................................................................
As stated elsewhere in this book, it is important to adopt a consistent coding style,
although in many ways it doesn’t matter which style you adopt. A consistent style makes
it easier to guess what you meant by a particular part of the code, and you avoid having
to look up whether you spelled the function with an initial cap the last time you
invoked it.
The following guidelines are arbitrary; they are based on the guidelines used in projects
done in the past, and they’ve worked well. You can just as easily make up your own, but
these will get you started.
As Emerson said, “Foolish consistency is the hobgoblin of small minds,” but having
some consistency in your code is a good thing. Make up your own, but then treat it as if
it were dispensed by the programming gods.
Indenting ........................................................................................................
If you use tabs, they should be three spaces. Be certain your editor converts each tab to
three spaces.
Braces ............................................................................................................
How to align braces can be the most controversial topic between C++ programmers.
Here are a few suggested tips:
- Matching braces should be aligned vertically.
- The outermost set of braces in a definition or declaration should be at the left mar-
gin. Statements within should be indented. All other sets of braces should be in line
with their leading statements. - No code should appear on the same line as a brace. For example,
if (condition==true)
{
j = k;
SomeFunction();
}
m++;
As stated, the alignment of braces can be controversial. Many C++ program-
mers believe you should put the opening brace on the same line as the com-
mand it is associated with and the closing brace lines up with the command:
NOTE