tags:

views:

217

answers:

6

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 simply const 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 of const is that compilers will generally store it in read-only memory that's backed by mmap 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, and stderr 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 a const pointer (not pointer-to-const) here fixes all the problems: extern FILE *const stdin;, where the const pointer is initialized to point to the pre-defined object (which itself is likely declared static) 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?

+6  A: 

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.

DuFace
While this works, I don't see the advantage over `#define my_inport (*(unsigned char const volatile *)0x00FA)` and then being able to just do `c=my_inport;` My version would probably compile to smaller/more efficient code because it's a constant expression, whereas the version with `const` variables might actually load the address indirectly each time it's used.
R..
This is basically the age old argument of `#define` constants versus `const` constants. In general, neither one is better or worse than the other. It's just that one is a language construct and one is a preprocessor command.It is often overlooked that a programming language is nothing more than a set of instructions for a program to interpret. In the case of C, the program is a compiler whose job is to produce optimised assembly code. So using language constructs should provide it with more information and allow it to produce a more relevant result. However, this is lost with `#define`s.
DuFace
+1  A: 
  • 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 is struct and union 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 a size_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 of CK_ATTRIBUTE, which is basically defined as

    typedef 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)},
    ... };
    
Gilles
Yeah but they'll complain even louder if you try to assign a value to a true constant expression, e.g. `1=2;`...
R..
@R..: but constant expressions (`#define`d, I presume?) are only possible in very specific cases.
Gilles
I've mentioned the only cases I can think of where `#define` wouldn't work better in the question. Can you think of some I'm missing? That's what I'm looking for.
R..
@R..: ok, I understand your focus better now, I've rewritten my answer with examples.
Gilles
+1  A: 

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.

Aidan Cully
Yeah I left out the big one - `const` data structures for state machines, lookup tables, etc. Duh..
R..
+2  A: 

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 ;-)

Steve Jessop
Why didn't you declare `value` to be `const` as well, for the same reason?
caf
@caf: forgot, thanks. I might especially want to declare `last` const defensively, because it's of the same type as `first`, which I do plan to modify. Since `value` is of a different type, there's slightly less benefit in making it const. Than again, it is of the same type as `*first`, which I *am* modifying. You're right, no reason not to other than the additional code. The same applies to non-parameter automatic variables - if you make 'em const, then anyone reading the code has less potentially-mutable state to worry about, and can use that bit of brain for something else.
Steve Jessop
A: 

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.)

detly
+2  A: 

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, in addition to its regular meaning, keeps locally allocated memory regions accounted.

eel ghEEz