Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigned `nullptr` to `bool` type. Which compiler is correct?

I have a following snippet of code that assigned nullptr to bool type.

#include <iostream>

int main()
{
    bool b = nullptr;
    std::cout << b;
}

In clang 3.8.0 working fine. it's give an output 0. Clang Demo

But g++ 5.4.0 give an error:

source_file.cpp: In function ‘int main()’:
source_file.cpp:5:18: error: converting to ‘bool’ from ‘std::nullptr_t’ requires direct-initialization [-fpermissive]
         bool b = nullptr;

Which compiler is correct?

like image 213
msc Avatar asked Oct 18 '17 17:10

msc


People also ask

What does nullptr mean in C++?

The nullptr keyword represents a null pointer value. Use a null pointer value to indicate that an object handle, interior pointer, or native pointer type does not point to an object. Use nullptr with either managed or native code.

Is nullptr a Falsy in C++?

2.4, new clause) 1 The type nullptr_t may be converted to bool or to a pointer type. The result is false or a null pointer value, respectively.

Does nullptr return false?

- In the context of a direct-initialization, a bool object may be initialized from a prvalue of type std::nullptr_t, including nullptr. The resulting value is false.


1 Answers

From the C++ Standard (4.12 Boolean conversions)

1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

So this declaration

bool b( nullptr );

is valid and this

bool b = nullptr;

is wrong.

I myself pointed out already this problem at isocpp

like image 92
Vlad from Moscow Avatar answered Oct 10 '22 10:10

Vlad from Moscow