What are some practical uses for const-qualified variables in C?
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.U开发者_开发问答sing
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?
const
is quite often used in embedded programming for mapping onto GPIO pins of a microcontroller. For example:
typedef unsigned char const volatile * const tInPort; typedef unsigned char * const tOutPort; tInPort my_input = (tInPort)0x00FA; tOutPort my_output = (tOutPort)0x00FC;
Both of these prevent the programmer from accidentally changing the pointer itself which could be disastrous in some cases. The tInPort
declaration also prevents the programmer from changing the input value.
Using volatile
prevents the compiler from assuming that the most recent value for my_input
will exist in cache. So any read from my_input
will go directly to the bus and hence always read from the IO pins of the device.
For example:
void memset_type_thing(char *first, char *const last, const char value) {
while (first != last) *(first++) = value;
}
The fact that last
can't be part of a constant-expression is neither here nor there. const
is part of the type system, used to indicate a variable whose value will not change. There's no reason to modify the value of last
in my function, so I declare it const
.
I could not bother declaring it const
, but then I could not bother using a statically typed language at all ;-)
PC-lint warning 429 follows from the expectation that a local pointer to an allocated object should be consumed
- by copying it to another pointer or
- by passing it to a "dirty" function (this should strip the "custodial" property of the pointer) or
- by freeing it or
- by passing it up the caller through a return statement or a pass-by-pointer parameter.
By "dirty" I mean a function whose corresponding pointer parameter has a non-const base type. The description of the warning absolves library functions such as strcpy() from the "dirty" label, apparently because none of such library functions takes ownership of the pointed object.
So when using static analysis tools such as PC-lint, the const qualifier of parameters of called functions keeps locally allocated memory regions accounted.
const
can be useful for some cases where we use data to direct code in a specific way. For example, here's a pattern I use when writing state machines:
typedef enum { STATE1, STATE2, STATE3 } FsmState;
struct {
FsmState State;
int (*Callback)(void *Arg);
} const FsmCallbacks[] = {
{ STATE1, State1Callback },
{ STATE2, State2Callback },
{ STATE3, State3Callback }
};
int dispatch(FsmState State, void *Arg) {
int Index;
for(Index = 0; Index < sizeof(FsmCallbacks)/sizeof(FsmCallbacks[0]); Index++)
if(FsmCallbacks[Index].State == State)
return (*FsmCallbacks[Index].Callback)(Arg);
}
This is analogous to something like:
int dispatch(FsmState State, void *Arg) {
switch(State) {
case STATE1:
return State1Callback(Arg);
case STATE2:
return State2Callback(Arg);
case STATE3:
return State3Callback(Arg);
}
}
but is easier for me to maintain, especially in cases where there's more complicated behavior associated with the states. For example, if we wanted to have a state-specific abort mechanism, we'd change the struct definition to:
struct {
FsmState State;
int (*Callback)(void *Arg);
void (*Abort)(void *Arg);
} const FsmCallbacks[] = {...};
and I don't need to modify both the abort
and dispatch
routines for the new state. I use const
to prevent the table from changing at runtime.
A
const
variable is useful when the type is not one that has usable literals, i.e., anything other than a number. For pointers, you already give an example (stdin
and co) where you could use#define
, but you'd get an lvalue that could easily be assigned to. Another example isstruct
andunion
types, for which there are no assignable literals (only initializers). Consider for instance a reasonable C89 implementation of complex numbers:typedef struct {double Re; double Im;} Complex; const Complex Complex_0 = {0, 0}; const Complex Complex_I = {0, 1}; /* etc. */
Sometimes you just need to have a stored object and not a literal, because you need to pass the data to a polymorphic function that expects a
void*
and asize_t
. Here's an example from the cryptoki API (a.k.a. PKCS#11): many functions require a list of arguments passed as an array ofCK_ATTRIBUTE
, which is basically defined astypedef struct { CK_ATTRIBUTE_TYPE type; void *pValue; unsigned long ulValueLen; } CK_ATTRIBUTE; typedef unsigned char CK_BBOOL;
so in your application, for a boolean-valued attribute you need to pass a pointer to a byte containing 0 or 1:
CK_BBOOL ck_false = 0; CK_ATTRIBUTE template[] = { {CKA_PRIVATE, &ck_false, sizeof(ck_false)}, ... };
They can be used for memory-mapped peripherals or registers that cannot be changed by user code, only some internal mechanism of the microprocessor. Eg. on the PIC32MX, certain registers indicating program state are qualified const volatile
- so you can read them, and the compiler won't try to optimise out, say, repeated accesses, but your code cannot write to them.
(I don't any code to hand, so I can't cite a good example right now.)
精彩评论