Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is converting a bool (false) to a pointer legal in C++?

I've recently stumbled unto something strange: converting a boolean to pointer works in Visual Studio 2013 and 2015 but not on GCC nor Clang (tried in 3.5).

#include <iostream>

using namespace std;

void foo(int *ptr)
{
    std::cout << "foo";
}

int main()
{
   foo(false);
}

Error in GCC:

    main.cpp: In function 'int main()':
    main.cpp:13:13: error: cannot convert 'bool' to 'int*' for argument '1' to 'void foo(int*)'
    foo(false);
             ^

My guess is that false is converted to 0 which is equivalent to NULL. Replacing the call to foo with foo(true) causes the compilation to fail with every compiler.

So my question is: is this code supposed to compile? I fail to see the benefit of converting false to a pointer, it seems to me that it would only be the cause of bugs after misuse / refactoring etc

like image 538
Uflex Avatar asked May 31 '16 09:05

Uflex


1 Answers

This should not be accepted since C++11.

See Pointer conversions (emphasis mine):

A null pointer constant (see NULL), can be converted to any pointer type, and the result is the null pointer value of that type. Such conversion (known as null pointer conversion) is allowed to convert to a cv-qualified type as a single conversion, that is, it's not considered a combination of numeric and qualifying conversions.

Note since C++11 a null pointer constant might be an integer literal with value zero (or a prvalue of type std::nullptr_t), while false is not, it's a boolean literal.

And until C++11 null pointer constant is defined as an integral constant expression rvalue of integer type that evaluates to zero, while false is fine. (GCC will give a warning for it.)

From the standard, $4.10/1 Pointer conversions [conv.ptr] (emphasis mine)

A null pointer constant is an integer literal (2.13.2) with value zero or a prvalue of type std::nullptr_t.

The conversion of a null pointer constant to a pointer to cv-qualified type is a single conversion, and not the sequence of a pointer conversion followed by a qualification conversion (4.4).

like image 197
songyuanyao Avatar answered Sep 20 '22 09:09

songyuanyao