Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Objects that are const-qualified have scope and can be type-checked by the compiler. Because these are named objects (unlike macro definitions), some debugging tools can show the name of the object. The object also consumes memory.

A const-qualified objects object allows you to specify the exact type of the constant. For example:

Code Block
unsigned int const buffer_size = 256;

...

Wiki Markup
{{const}}\-qualified objects are likely to incur some runtime overhead  \[[Saks 01b|AA. C References#Saks 02]\]. Most C compilers, for example, allocate memory for {{const}}\-qualified objects. {{const}}\-qualified objects declared inside a function body may have automatic storage duration. If so, the compiler will allocate storage for the object, and it will be on the stack. As a result, this storage will need to be allocated and initialized each time the containing function is invoked.

...

A preprocessing directive of the form:

# define identifier replacement-list

...

C programmers frequently define symbolic constants as object-like macros. For example, the code:

Code Block
#define buffer_size 256

...

In this compliant solution, the integer literal is replaced with an enumeration constant (see DCL00-A. Const-qualify immutable objects).

...

Compliant Solution (sizeof)

Frequently, it is possible to obtain the desired readability by using a symbolic expression composed of existing symbols rather than by defining a new symbol. For example, a sizeof expression can work just as well as an enumeration constant (see EXP09-A. Use sizeof to determine the size of a type or variable).

...

Wiki Markup
Using the {{sizeof}} expression in this example reduces the total number of names declared in the program, which is generally a good idea \[[Saks 02|AA. C References#Saks 02]\].  The {{sizeof}} operator is almost always evaluated at compile time (except in the case of variable -length arrays).

When working with sizeof(), keep in mind ARR01-A. Do not apply the sizeof operator to a pointer when taking the size of an array.

...

Replacing numeric constants with symbolic constants in this example does nothing to improve the readability of the code, and may actually make the code more difficult to read:.

Code Block
enum { TWO = 2 };     /* a scalar */
enum { FOUR = 4 };    /* a scalar */
enum { SQUARE = 2 };  /* an exponent */
x = (-b + sqrt(pow(b, SQUARE) - FOUR*a*c))/ (TWO * a);

...