"Narrowing conversion from 'int' to 'char' inside { }" for legal values when cross compiling

Andy Thomas picture Andy Thomas · Jul 26, 2015 · Viewed 34.5k times · Source

I have a C++ project that I compile both using g++ on my machine (compiling to "host") and to an ARM processor using a cross compiler (in my case arm-cortex_a8-linux-gnueabi-g++). I am in the process of converting to C++0x/11 standart and there is an error I get when compiling initialization list, which I was able to reproduce in the following snippet:

int main(void) {
    char c[1] = {-108};
}

This program is seemingly correct as -108 is a legal value for a char. Compiling this with g++ yields no error with the following command line:

g++ example.cc -std=c++0x

However, when I compile with the cross-compiler, like so:

arm-cortex_a8-linux-gnueabi-g++ example.cc -std=c++0x

I get the following error:

example.cc: In function 'int main()':
example.cc:2:22: error: narrowing conversion of '-0x0000000000000006c' from 'int' to 'char' inside { } [-fpermissive]

Since the value is legal, this seems like a bug. Can you explain why I get this error and what to do to solve it?

Edit: note that using positive values (e.g., 108) is legal and does not result in an error on both compilers.

Answer

Barmar picture Barmar · Jul 26, 2015

When you declare a variable as char, it's implementation-dependent whether it's signed or unsigned. If you need to be able to store negative values, you should declare it signed explicitly, rather than relying on the implementation-defined default.

signed char c[1] = { -108 };