Cannot initialize a member subobject of type 'const signed char *' with an lvalue of type 'const char [X]'

I have the following code :

typedef       signed char         Char;

static const struct MyStruct
{
    const Char* str;
    // Other fields
}
myList[] =
{
    {"none", /* Other fields */},
    {"main", /* Other fields */},
}

But I have compilation errors :

Cannot initialize a member subobject of type 'const Char *' (aka 'const signed char *') with an lvalue of type 'const char [X]

X is string length

It's OK when I replace Char by char, but how can I use signed char ?

2 answers

  • answered 2017-10-11 10:17 Bathsheba

    "none", for example is a const char[5] type. Under certain circumstances, this can decay to a const char*.

    Irrespective as to whether char is signed or unsigned on your platform, char, signed char, and unsigned char are always distinct types.

    C++ does not allow direct decay of a const char[N] type to anything other than a const char* (or a pointer to a typedef of const char*), so in your case it is required to issue a diagnostic.

    In C++ you have so many other alternatives: std::string being the obvious choice in your case.

    To examine the type of char you have, use

    std::numeric_limits<char>::is_signed
    

    from <limits>.

  • answered 2017-10-11 10:24 user2079303

    but how can I use signed char ?

    By using an array of signed char instead of a string literal:

    signed char none[] = {'n','o','n','e','\0'};
    
    ...
    
    myList[] =
    {
        {none, /* Other fields */},
        ...
    }
    

    Note that char (the type of the character literal) may be unsigned and if the value is not representable by signed char, then the resulting value will be implementation defined.