4

I have the following code, which compiles in Visual C++ 2012.

#include <string> void func(std::string str) { } void my_func() { func(false); } 

The boolean 'false' is implicity passed into the string constructor

string(const char* _Ptr) 

And then the pointer is null (because false = 0). Why does this compile, and should it compile according to the C++11 standard?

5
  • That shouldn't compile. Commented Jul 1, 2015 at 14:01
  • Only the literal 0 can be a null pointer constant. This shouldn't compile indeed. Commented Jul 1, 2015 at 14:02
  • Interestingly it doesn't compile if you pass 'true' Commented Jul 1, 2015 at 14:03
  • Surprisingly GCC compiles it too, but not without spewing "warning: converting 'false' to pointer type for argument 1 of [...] [-Wconversion-null]" Commented Jul 1, 2015 at 14:04
  • You can see GCC compiling and running it here and here Commented Jul 1, 2015 at 14:06

1 Answer 1

6

MSVC is mistakenly treating false as a null pointer constant. However, according to N4140, §4.10 [conv.ptr]/1 (emphasis mine):

A null pointer constant is an integer literal with value zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type.

The wording changed a bit from C++11, and you can find that discussion here. The verdict there was that it was an error in C++11 as well.

For visibility, TartanLlama provided the definition of "integer literal" below, according to [lex.icon]/1:

An integer literal is a sequence of digits that has no period or exponent part, with optional separating single quotes that are ignored when determining its value.

Sign up to request clarification or add additional context in comments.

4 Comments

I believe you are wrong because bool is an integral type (§3.9.1/7)
@KonradRudolph bool is an integral type, but false is not an integer literal.
@TartanLlama How so? It’s an integer and it’s a literal, and its value is 0.
@KonradRudolph [lex.icon]/1 "An integer literal is a sequence of digits that has no period or exponent part, with optional separating single quotes that are ignored when determining its value."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.