"Narrowing the conversion from" int "to" char "inside {}" for legal values ​​in cross-compilation

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

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

This program seems to be correct, since -108 is the legal value for char . Compiling with g++ does not result in an error on the following command line:

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

However, when I compile using a cross-compiler, for example:

 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 an error. 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 for both compilers.

+8
c ++ linux c ++ 11 cross-compiling
source share
3 answers

When you declare a variable as char , it depends on the implementation, whether it is signed or not. If you need to keep negative values, you must explicitly declare it signed , and not rely on the default option.

 signed char c[1] = { -108 }; 
+14
source share

Because the value is legal

How do you know that? char signature is an implementation. And if it is unsigned, your code is poorly formed by narrowing it down - Β§8.5.4 / 7:

Narrowing a transform is an implicit transform
[...]
(7.4) - from an integer type [...] to an integer type that cannot represent all the values ​​of the source type , except where the source is a constant expression, the value of which after the whole stock will fit into the target type.

Β§8.5.1 / 2:

If the expression initializer-expression is an expression, and to transform the expression requires a narrowing transformation (8.5.4), the program is poorly formed.

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

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

... guaranteed to work.

+9
source share

This should be even better:

 signed char c[] = { (signed char)(-108) }; 

Because in parentheses, the default value can be considered an int value.

-one
source share

All Articles