cconstantsidioms

idiomatic C for const double-pointers


I am aware that in C you can't implicitly convert, for instance, char** to const char** (c.f. C-Faq, SO question 1, SO Question 2).

On the other hand, if I see a function declared like so:

void foo(char** ppData);

I must assume the function may change the data passed in. Therefore, if I am writing a function that will not change the data, it is better, in my opinion, to declare:

void foo(const char** ppData);

or even:

void foo(const char * const * ppData);

But that puts the users of the function in an awkward position. They might have:

int main(int argc, char** argv)
{
    foo(argv); // Oh no, compiler error (or warning)
    ...
}

And in order to cleanly call my function, they would need to insert a cast.

I come from a mostly C++ background, where this is less of an issue due to C++'s more in-depth const rules.

What is the idiomatic solution in C?

  1. Declare foo as taking a char**, and just document the fact that it won't change its inputs? That seems a bit gross, esp. since it punishes users who might have a const char** that they want to pass it (now they have to cast away const-ness)

  2. Force users to cast their input, adding const-ness.

  3. Something else?


Solution

  • 2 is better than 1. 1 is pretty common though, since huge volumes of C code don't use const at all. So if you're writing new code for a new system, use 2. If you're writing maintenance code for an existing system where const is a rarity, use 1.