As has been discussed in several recent questions, declaring const
-qualified variables in C (as opposed to const
variables in C++, or pointers to const
in C) usually serves very little purpose. Most importantly, they cannot be used in constant expressions.
With that said, what are some legitimate uses of const
qualified variables in C? I can think of a few which have come up recently in code I've worked with, but surely there must be others. Here's my list:
Using their addresses as special sentinel values for a pointer, so as never to compare equal to any other pointer. For example:
char *sentinel(void) { static const char s; return &s; }
or simplyconst char sentinel[1];
Since we only care about the address and it actually wouldn't matter if the object were written to, the only benefit ofconst
is that compilers will generally store it in read-only memory that's backed bymmap
of the executable file or a copy of the zero page.Using
const
qualified variables to export values from a library (especially shared libraries), when the values could change with new versions of the library. In such cases, simply using#define
in the library's interface header would not be a good approach because it would make the application dependent on the values of the constants in the particular version of the library it was built with.Closely related to the previous use, sometimes you want to expose pre-defined objects from a library to the application (the quintessential examples being
stdin
,stdout
, andstderr
from the standard library). Using that example,extern FILE __stdin; #define stdin (&__stdin)
would be a very bad implementation due to the way most systems implement shared libraries - usually they require the entire object (here,FILE
) to be copied to an address determined when the application is linked, and introduce a dependency on the size of the object (the program will break if the library is rebuilt and the size of the object changes). Using aconst
pointer (not pointer-to-const
) here fixes all the problems:extern FILE *const stdin;
, where theconst
pointer is initialized to point to the pre-defined object (which itself is likely declaredstatic
) somewhere internal to the library.Lookup tables for mathematical functions, character properties, etc. This is the obvious one I originally forgot to include, probably because I was thinking of individual
const
variables of arithmetic/pointer type, as that's where the question topic first came up. Thanks to Aidan for triggering me to remember.As a variant on lookup tables, implementation of state machines. Aidan provided a detailed example as an answer. I've found the same concept is also often very useful without any function pointers, if you can encode the behavior/transitions from each state in terms of a few numeric parameters.
Anyone else have some clever, practical uses for const
-qualified variables in C?