Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 285
Andy Thomas Avatar asked Jul 26 '15 08:07

Andy Thomas


2 Answers

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 };
like image 69
Barmar Avatar answered Sep 26 '22 03:09

Barmar


Since the value is legal

How do you know that? chars signedness is implementation defined. And if it's unsigned, your code is ill-formed by narrowing - §8.5.4/7:

A narrowing conversion is an implicit conversion
[…]
(7.4) — from an integer type […] to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.

§8.5.1/2:

If the initializer-clause is an expression and a narrowing conversion (8.5.4) is required to convert the expression, the program is ill-formed.

However, if you need a signed char, use signed char.

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

…is guaranteed to work.

like image 31
Columbo Avatar answered Sep 27 '22 03:09

Columbo