0

I am working with old code and I got an error at every -1 when compiling using newer C++ standard.

constant expression evaluates to -1 which cannot be narrowed to type 'char' [-Wc++11-narrowing]

Here is the snippet code

typedef struct {
    //short     len;
    //unsigned short cw;
    char        x, y, v, w;
} testStruct;

const testStruct testArr[] = {
    {   1,  -1,   0,   0},
    {  -1,   1,   0,   0},
    {   0,   0,  -1,   1},
    {   0,   1,  -1,   0},
    {   0,  -1,   1,   0},
    {   0,   0,   1,  -1},
    {   1,   1,   0,   0},
    {   0,   0,  -1,  -1},
    {  -1,  -1,   0,   0},
    {   0,  -1,  -1,   0},
    {   1,   0,  -1,   0},
    {   0,   1,   0,  -1},
    {  -1,   0,   1,   0},
    {   0,   0,   1,   1},
    {   1,   0,   1,   0},
    {   0,  -1,   0,   1},
    {   0,   1,   1,   0},
    {   0,   1,   0,   1},
    {  -1,   0,  -1,   0},
    {   1,   0,   0,   1},
    {  -1,   0,   0,  -1},
    {   1,   0,   0,  -1},
    {  -1,   0,   0,   1},
    {   0,  -1,   0,  -1}
};

I've tried to change the code and bracket to parentheses following warning: narrowing conversion C++11 , but I still got the same error. Is there any solution without reverting back to old C++ standard?

gameon67
  • 3,981
  • 5
  • 35
  • 61

1 Answers1

1

To override the compiler, you have to write static_cast<char>(-1)

Some things are no longer acceptable with the newer C++ standards, so you have to find a more modern way to do things...

U. W.
  • 414
  • 2
  • 10
  • 1
    `constexpr char XX = static_cast(-1);` and then replace all the `-1` in the table with `XX` may be more legible and retain the table columnar formatting better. – Eljay Jan 22 '21 at 13:54
  • is it okay to just change char type in struct or I have to cast signed char to `-1 `only? – gameon67 Jan 22 '21 at 14:11
  • @Eljay: Of course I would do it the same way. This would also get rid of the magic number -1 and give it a more meaningful name! – U. W. Jan 25 '21 at 07:55