You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Next »

Place const as the rightmost declaration specifier when declaring constants. Although placing const to the right of the type specifier in declarations conflicts with conventional usage, it is less likely to result in common errors and should be the preferred approach.

Non-Compliant Code Example

In this non-compliant code example, the const type qualifier is positioned to the left of the type specifier NTCS in the declaration of p.

typedef char *NTCS;

const NTCS p;

This can lead to confusion when programmers assume a strict text replacement model similar to the one used in macros applies in this case. This leads you to think that p is a "pointer to const char" which is the incorrect interpretation. In this example, p is a actually a const pointer to char.

Compliant Solution

Placing const as the rightmost declaration specifier makes the meaning of the declaration clearer as in this compliant example.

typedef char *NTCS;

NTCS const p;

Even if a programmer (incorrectly) thinks of this of this as text replacement, char * const p will be correctly interprested as a const pointer to char.

Exceptions

Placing const to the left of the type name may be appropriate to preserve consistency with existing code.

References

  • No labels