Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
284
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Coding with Style

Good names convey information about their purpose without making the code unreadable.

Using Language Features with Style

The C++ language lets you do all sorts of terribly unreadable things. Take a look at this wacky code:

i++ + ++i;

With all the power that the C++ language offers, it is important to consider how the language features can be used towards stylistic good instead of evil.

Use Constants

Bad code is often littered with “magic numbers.” In some function, the code is dividing by 24. Why 24? Is it because there are 24 hours in a day? Or because the average price of cheese in New Brunswick is $24? The language offers constants to give a symbolic name to a value that doesn’t change, such as 24.

const int kAveragePriceOfCheeseInNewBrunswick = 24;

Take Advantage of const Variables

The const keyword in C++ is basically syntactic sugar (a techie term for syntax that helps the programmer more than the program) for “don’t change this variable.” Proper use of const is more about style than about programming correctness. There are certainly experienced C++ programmers who have never found a reason to use const and feel that it has not had a negative impact on their careers. Like many parts of C++, const exists to help the programmer more than the program. It is your responsibility to use const and to use it correctly. The ins and outs of const are covered in Chapter 12. Below is the prototype for a function that tells the caller that it will not change the content of the C-style string that is passed in.

void wontChangeString(const char* inString);

Use References Instead of Pointers

Traditionally, C++ programmers learn C first. If you have taken this path, you probably recognize that references don’t really add any new functionality to the language. They merely introduce a new syntax for functionality that pointers could already provide. In C, pointers were the only pass-by-reference mechanism, and they certainly worked just fine for many years. Pointers are still required in some cases, but in many situations you can switch to references.

There are several advantages to using references rather than pointers. First, references are safer than pointers because they don’t deal directly with memory addresses and cannot be NULL. Second, references are more stylistically pleasing than pointers because they use the same syntax as stack variables,

151