...
Code Block |
---|
|
const float pi = 3.14159f;
float degrees;
float radians;
/* ... */
radians = degrees * pi / 180;
|
Non-Compliant Code Example
Wiki Markup |
---|
In this example, adapted from \[[Dewhurst 02|AA. C++ References#Dewhurst 02]\] Gotcha #25, a macro is used to define a maximum value, but there is no type information associated with the macro. |
Code Block |
---|
|
#define MAX (1<<16)
// ...
void f(int);
void f(long);
// ...
f(MAX); // which f?
|
The value 1 << 16
could be an int
or a long
depending on the platform. As a result, this code becomes platform dependent.
Compliant Solution
Using a constant associates type information with the value and eliminates the possibility of confusion.
Code Block |
---|
|
int const max = 1<<16;
// ...
void f(int);
void f(long);
// ...
f(max);
|
Exceptions
DCL00-EX1: It is acceptable to define valueless macros to serve as 'inclusion guards'. That is, the macro serves to control the multiple inclusion of header files, as in the following example:
Code Block |
---|
#ifndef SOME_HEADER_H
#define SOME_HEADER_H
... // content of header file
#endif
|
See PRE06-C. Enclose header files in an inclusion guard for more information on inclusion guards.
Risk Assessment
Failing to const
-qualify immutable objects can result in a constant being modified at runtime.
...