4

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 ?

A.Pissicat
  • 3,023
  • 4
  • 38
  • 93

2 Answers2

5

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

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
3

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326