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
- ISO/IEC 9899-1999 Section 6.7 Declarations
- Dan Saks. const T vs.T const. Embedded Systems Programming. Pg. 13-16. February 1999. http://www.dansaks.com/articles/1999-02%20const%20T%20vs%20T%20const.pdf