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?

6
  • 3
    What compiler are you using? What flags are you passing? Commented Feb 9, 2019 at 0:00
  • related stackoverflow.com/questions/27507361/… Commented Feb 9, 2019 at 0:01
  • 1
    Looks like it compiles on gcc (why?), but not on msvc and clang Commented Feb 9, 2019 at 0:04
  • 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] Commented Feb 9, 2019 at 0:09
  • 1
    @drescherjm Page 139, 4th Edition, section 6.2.2. (4th printing, if that matters.) Commented Feb 9, 2019 at 0:27

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.