#include <stdio.h>


#if 1
//! Set Pin string
const char* const ONCLI_SET_PIN_CMD_STR = "set pin";
#endif

const char* const SINGLE_APP_STRINGS[] =
{
    ONCLI_SET_PIN_CMD_STR
};


int main()
{
    printf("%s\n", SINGLE_APP_STRINGS[0]);
    getchar(); // pause
    return 0;
}

Line 12 Error message...

12|error: initializer element is not constant
12|error: (near initialization for 'SINGLE_APP_STRINGS[0]')
=== Build finished: 2 errors, 0 warnings ===

Compiles and runs just fine in C++. Everything's read-only. No changes are needed or desired or attempted on the strings or on the array. What's the problem and how can I fix it?

I did a little typecasting and got it from an error to a warning.

#include <stdio.h>


#if 1
//! Set Pin string
const char* const ONCLI_SET_PIN_CMD_STR = "set pin";
#endif

const char** const SINGLE_APP_STRINGS[] =
{
    &ONCLI_SET_PIN_CMD_STR
};


int main()
{
    printf("%s\n", *(SINGLE_APP_STRINGS[0]));
    getchar(); // pause
    return 0;
}

Change line 6 to this...

const char* ONCLI_SET_PIN_CMD_STR = "set pin";

and the warning goes away. I'd like to avoid doing that if possible since all the other strings are const char* const types.


This seems to work too...

#include <stdio.h>



#if 1
//! Set Pin string
const char* const ONCLI_SET_PIN_CMD_STR = "set pin";
#endif

const char* const* const SINGLE_APP_STRINGS[] =
{
    &ONCLI_SET_PIN_CMD_STR
};


int main()
{
    printf("%s\n", *(SINGLE_APP_STRINGS[0]));
    getchar(); // pause
    return 0;
}

No warnings. Runs fine. Seems like there's an extra "const" in there? One that wasn't needed in C++?

What's the problem and how can I fix it?

const in C doesn't mean the same thing as const in C++. In C, the object is read-only at the source level, but does not constitute a compile-time constant like it does in C++. Your error is coming from this clause of the C standard:

All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

So with your original code, a direct fix is to use a define rather than a const object for the string value:

#if 1
//! Set Pin string
#define ONCLI_SET_PIN_CMD_STR "set pin"
#endif

Thanks. In order to make it compile without warnings and make it as consistent as possible with the rest of the code, which uses const char* const everywhere, I ended up making it an array of pointers to char*, then dereferencing them when using the array. Can't remember if it's exactly like it is in my last post, but if not, it's close. I just stuck as many consts in there as possible with a big "This is not to changed!" comment, so at least anyone reading the code knows the intent. Solved.

This question has already been answered. Start a new discussion instead.