cpointersinitialization

Is there an alternative syntax to initialize a const pointer to const data?


I have a piece of embedded C software that requires multiple const pointers to const data. So far I've been repeating two lines of code to initialize them:

const int data = 0xF0; // const int
const int* const buffer = &data; // const pointer to const int

Previously I used lots of type casts, but found that too error prone while reviewed by teammates. I'm open to using them if I can find a way to use them clearly and consistently. I also need to avoid discarding my const qualifier when passing to functions, as discarding this has actually caused one bug in development already.


Solution

  • You can define the pointer and the data in a single declaration (albeit not readable and not recommended:

    const int data = 0xF0, * const buffer = &data;
    

    Using C99 compound literals, you can also write:

    const int * const buffer = (const int[]){ 0xF0 };
    

    or

    const int * const buffer = (const int[1]){ 0xF0 };
    

    or

    const int * const buffer = &(const int){ 0xF0 };
    

    Note that the order of the const and int keywords does not matter and it may be more readable to put the const keyword closer to the * it qualifies:

    int const * const buffer = (int const []) { 0xF0 };
    

    The question is: Why do you need a pointer at all? If the pointer is constant, it cannot be changed to point to something else, hence why define a pointer when you can pass &data directly?

    Removing the const qualifier for function calls is an indication of design flaws: a function taking a pointer to data that it does not modify should have the argument defined as whatevertype const *arg and you do not need any cast when passing the address of the data, be it const qualified or not. If the function does modify the data it gets a pointer to, passing it data that is defined as const will trigger undefined behavior upon modification as the data may be located in read only memory.