The concept of narrowing seems pretty straight-forward. However, could someone please explain why some of the code below causes “narrowing” compiler errors and others don’t?
This code produces errors where expected:
constexpr int a = 255;
unsigned char b = a; // OK
unsigned char c = a + 1; // Error... expected
This code doesn’t produce errors, but may be ok:
int d = 256;
unsigned char e = d; // Maybe OK because 'd' is not constexpr
This code should generate errors (unless I’m missing something):
int f = 42.0; // Maybe OK because no fractional part
int g = 42.1; // OK... should fail!!
constexpr float h = 42.7;
int i = h; // OK... should fail???
I’m using g++ 4.6.2. I searched the GCC bug database and didn’t find anything related. Thanks!
To be honest, with your samples I see little wrong.
However, there are a number of cases where the compiler seems to accept ‘violations’ of the standard conversion rules…:
Initializer lists (§ 8.5.4)
However I spotted this one in the standard:
For initialzer lists, the following is not allowed (§ 8.5.4, under 3.)
Under 6. it goes on to give a general list of examples:
Interestingly, g++ 4.6.1 with
--std=c++0x -Wall -pedanticcatches only one of these violations:Outside initializer lists…
I don’t think the truncation of a float to an int is considered
narrowing.It is just a well-defined conversion, much like