pololu/pololu-led-strip-arduino

Narrowing conversion inside { } is ill-formed

Closed this issue · 1 comments

The way we initialize the color structs in the demo code is actually "ill-formed" in C++11. For example:

(rgb_color){ 0, 255 - x, 0 };

The problem is that the middle field is a uint8_t, but the value we are trying to stick into it is actually an int because of integer promotion. I found out because I tried to compile code like that in Atmel Studio, which is using a pretty modern version of the GCC C++ compiler and got warnings like this:

narrowing conversion of '(255 - ((int)x))' from 'int' to 'unsigned char' inside { } is ill-formed in C++11 [-Wnarrowing]

When the Arduino IDE starts using a modern compiler and people get this warning, we should introduce a macro or inline function like this:

#define color(r, g, b) ((rgb_color){ (uint8_t)(r), (uint8_t)(g), (uint8_t)(b) })

It is OK to have a narrowing happen in a normal assignment, like c = a + b, but if narrowing happens during an initializer they think that is special and deserves a warning.

This is fixed in version 4.2.0 with the new constructors for rgb_color.