Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No warning for narrowing when initializing with parentheses

Tags:

c++

gcc

c++11

g++

I stumbled upon a perplexing situation where I have found an obvious narrowing conversion, but I'm disappointed that the compiler (gcc-4.7.2) did not raise a warning despite -Wall -Wnarrowing -pedantic flags. Please see the following program:

struct A {
  int m;
  A( int m ) : m(m) {};
};

int main() {
  unsigned long v = 0;
  A a1(v);  // narrowing, but no warning (should this not cause a warning?)
  A a2{v};  // narrowing, warning raised (expected)
}

Initialization of a1 seems to fly without so much as a peep from the compiler. Just to make sure I wasn't going insane, I tried to initialize a1 in the same manner, but with braces instead of parens. The compiler warns about narrowing in the second case, as was expected.

To be clear: I'm not asking about the legality of narrowing conversions in initialization-lists. I know that's not legal--the curly-braced initialization of a2 was a mere sanity-check. My question is unrelated to initialization lists. This is not a duplicate question.

Should the compiler not warn me about narrowing for the initialization of a1?

like image 442
Iron Savior Avatar asked Jun 20 '13 15:06

Iron Savior


1 Answers

Wsign-conversion will generate a warning for that line of code - -Wconversion will not when unsigned long and int have the same size (which is true on many platforms, even some 64-bit platforms). For C code, -Wconversion will enable -Wsign-conversion implicitly, but that doesn't happen with C++ for some reason.

If you change the type of v to long long, -Wconversion by itself will generate a warning (assuming that int is 32-bits).

like image 113
Michael Burr Avatar answered Nov 15 '22 05:11

Michael Burr