c++11pointersinitializationnullptr

Should you always initialize variables with NULL or nullptr?


I'm just a little bit confused.

When should I use nullptr?

I've read on some sites that it should always be used, but I can't set nullptr for a non-pointer for example:

int myVar = nullptr; // Not a pointer ofcourse

Should I always use NULL non-pointers and nullptr for pointers?

Thanks to any help! I'm very new to c++ 11 (and c++ overall).


Solution

  • Always use nullptr when initializing pointers to a null pointer value, that's what it is meant for according to draft n3485.

    [lex.nullptr] paragraph 1

    The pointer literal is the keyword nullptr. It is a prvalue of type std::nullptr_t. [ Note: std::nullptr_t is a distinct type that is neither a pointer type nor a pointer to member type; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or null member pointer value. [...] — end note ]

    Now onto the use of NULL.

    According to the same draft it shall be defined as follows.

    [diff.null] paragraph 1

    The macro NULL, [...] is an implementation-defined C ++ null pointer constant in this International Standard.

    and null pointer constant as follows.

    [conv.ptr] paragraph 1

    A null pointer constant is an integral constant expression [...] prvalue of integer type that evaluates to zero or a prvalue of type std::nullptr_t.

    That is, it is implementation-defined behavior whether NULL is defined as an integer prvalue evaluating to zero, or a prvalue of type std::nullptr_t. If the given implementation of the standard library chooses the former, then NULL can be assigned to integer types and it's guaranteed it will be set to zero, but if the later is chosen, then the compiler is allowed to issue an error and declare the program ill-formed.

    In other words, although conditionally valid [read IB], initializing an integer using NULL is most probably a bad idea, just use 0 instead.

    On the other hand, according to the above NULL is guaranteed to initialize pointers to a null pointer value, much like nullptr does, but while NULL is a macro, what accompanies several caveats, nullptr is prvalue of a specific type, for which type checking and conversion rules apply. That's mostly why nullptr should be prefered.