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?
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
-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]