1

I am studying "The C++ Programming language" by Bjarne Stroustrup. On page 139 it gives the following example of code that will not compile.

bool b2 {7}; // error : narrowing

When I tried this example it does compile. Can anyone explain why?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • 3
    What compiler are you using? What flags are you passing? – Stephen Newell Feb 09 '19 at 00:00
  • related https://stackoverflow.com/questions/27507361/narrowing-conversion-to-bool-in-list-initialization-strange-behaviour – drescherjm Feb 09 '19 at 00:01
  • 1
    Looks like it compiles on gcc (why?), but not on msvc and clang – darune Feb 09 '19 at 00:04
  • gcc may be being excessively permissive. It also allows assigning string literals to non-`const` `char` pointers and Variable Length Arrays. try compiling with `-pedantic` and see if it spits out a Standards compliance warning. – user4581301 Feb 09 '19 at 00:06
  • 2
    @user4581301 g++ up to version 8.2.0 does not complain, even with `-pedantic -std=c++11`. g++ 9.0.0 (pre-release, built from source) does complain: `error: narrowing conversion of ‘7’ from ‘int’ to ‘bool’ [-Wnarrowing]` – Keith Thompson Feb 09 '19 at 00:09
  • 1
    @drescherjm Page 139, 4th Edition, section 6.2.2. (4th printing, if that matters.) – Keith Thompson Feb 09 '19 at 00:27

1 Answers1

6

Most compilers (unfortunately IMHO) do not fully conform to the C++ standard in their default modes.

For g++ and clang++, you can use the options -std=c++11 -pedantic-errors to enforce the language requirements. However, the released versions of g++ do not catch this particular error, which is a flaw in g++.

Using g++ 8.2.0, the declaration incorrectly compiles with no diagnostics:

$ cat c.cpp
bool b2 {7};
$ g++ -std=c++11 -pedantic -c c.cpp
$

Using clang++ 6.0.0, the error is correctly diagnosed:

$ clang++ -std=c++11 -pedantic -c c.cpp
c.cpp:1:10: error: constant expression evaluates to 7 which cannot be narrowed to type 'bool' [-Wc++11-narrowing]
bool b2 {7};
         ^
c.cpp:1:10: note: insert an explicit cast to silence this issue
bool b2 {7};
         ^
         static_cast<bool>( )
1 error generated.
$

Using a newer (unreleased, built from source) version of gcc:

$ g++ -std=c++11 -pedantic -c c.cpp
c.cpp:1:11: error: narrowing conversion of ‘7’ from ‘int’ to ‘bool’  [-Wnarrowing]
    1 | bool b2 {7};
      |           ^
$

clang++ already correctly diagnoses this error. Expect g++ to do so in version 9.0.0 when it's released.

If you want the conversion to be done without a diagnosis, you can use one of the other initialization syntaxes, such as:

bool b1 = 7; // sets b1 to true, no diagnostic
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631