6.7a — Null pointers

Null values and null pointers

Just like normal variables, pointers are not initialized when they are instantiated. Unless a value is assigned, a pointer will point to some garbage address by default.

Besides memory addresses, there is one additional value that a pointer can hold: a null value. A null value is a special value that means the pointer is not pointing at anything. A pointer holding a null value is called a null pointer.

In C++, we can assign a pointer a null value by initializing or assigning it to the literal 0:

Because a null pointer evaluates to 0, it can be used inside a conditional to test whether the pointer is a null pointer or not:

Best practice: Initialize your pointers to a null value if you’re not giving them another value.

Dereferencing null pointers

In the previous lesson, we noted that dereferencing a garbage pointer would lead to undefined results. Dereferencing a null pointer also results in undefined behavior. In most cases, it will crash your application.

Conceptually, this makes sense. Dereferencing a pointer means “go to the address the pointer is pointing at and access the value there”. A null pointer doesn’t have an address. So when you try to access the value at that address, what should it do?

The NULL macro

C (but not C++) defines a special preprocessor macro called NULL that is #defined as the value 0. Even though this is not technically part of C++, its usage is common enough that it should work in every C++ compiler:

However, because NULL is a preprocessor macro and because it’s technically not a part of C++, best practice in C++ is to avoid using it.

nullptr in C++11

Note that the value of 0 isn’t a pointer type, so assigning 0 to a pointer to denote that the pointer is a null pointer is a little inconsistent. In rare cases, when used as a literal argument, it can even cause problems because the compiler can’t tell whether we mean a null pointer or the integer 0:

To address these issues, C++11 introduces a new keyword called nullptr. nullptr is both a keyword and an rvalue constant, much like the boolean keywords true and false are.

Starting with C++11, this should be favored instead of 0 when we want a null pointer:

C++ will implicitly convert nullptr to any pointer type. So in the above example, nullptr is implicitly converted to an integer pointer, and then the value of nullptr (0) assigned to ptr.

This can also be used to call a function with a nullptr literal:

Best practice: With C++11, use nullptr to initialize your pointers to a null value.

std::nullptr_t in C++11

C++11 also introduces a new type called std::nullptr_t (in header <cstddef>). std::nullptr_t can only hold one value: nullptr! While this may seem kind of silly, it’s useful in one situation. If we want to write a function that accepts a nullptr argument, what type do we make the parameter? The answer is std::nullptr_t.

You probably won’t ever need to use this, but it’s good to know, just in case.

6.8 -- Pointers and arrays
6.7 -- Introduction to pointers

23 comments to 6.7a — Null pointers

  • Matt

    So, based on what we know up to this point in the tutorials, if we want to call a function without any required parameters, is it still considered safe to just do:

    If so, I guess I'm not seeing any use for these things yet.  Reading some of the comments below it sounds like it will be clearer sometime in the future.


  • Bonez

    Is that ok?

    • nascardriver

      Hi Bonez!

      Uniform initializers (The ones with curly brackets) are good practice, use them whenever you can, they assure that you’re initializing a variable with a value of the right type.

      PS: Please edit your comments instead of deleting and re-posting them, the code will be highlighted correctly after refreshing the page.

    • Alex

      Yup, and I updated the lesson to use uniform initialization for all examples.

  • Joao Miguel Machado

    Hey, I have a question 🙂

    Could I use this type std::nullptr to overload a function?
    For example say I want to write a function to record audio from a microcontroller or something. And I turn the device on but record no data, which could be a nullptr. Then this function that I overload does something when gets the nullptr and the other overloaded function is called when I don't feed it with the nullptr.

    I don't see how this could be better than justa making a 'if', but could this be done?

    Thanks 😀

    • Alex

      Yes, like this:
      1) Overload a function using a pointer argument (of any type).
      2) Overload the same function with a std::nullptr_t argument.

      If you pass the function a valid pointer, it will match #1. If you pass in a null, #2 is a better match, so it should use that.

  • Astronoid

    Hello Alex,
    What is the difference between:


    ; and what is the mean of the second one, and thanks.

    • Alex

      The first parameter is a pointer, so the argument is passed by address.
      The second parameter is a reference to a pointer. This means the doSomething() function can change the address held by the argument passed into Ptr.

  • Joao Gueifao

    I got confused on why C++11 would define something like nullptr_t in the first place...

    Suggestion: At the section "std::nullptr_t in C++11", why not motivating its usefulness in something like overloaded methods that take a pointer as argument, which is something to be explained at a later lesson?

    By the way, thank you so much for your tutorial, it simply rocks!


    • Alex

      I don't discuss the motivations for std::nullptr_t here because I haven't talked about what an overloaded function is yet.

      But that's the primary case. Without std::nullptr_t, you can't disambiguate void somefcn(int) and void somefcn(*int) when calling somefcn(0). Is 0 an int or a null pointer?

  • alex be like


    introduction blablablablablablablabla

    some codes


    some thousand lines, 1 hour and a headache later
    rule: you won't need those. *insert troll face here*

    I love your tutorials
    you are the best.. 🙂

    • Alex

      Haha. If you think these programs are long, wait until you get to the comprehensive quiz for this chapter! 😉

      • J3ANP3T3R

        Question : the use of assigning nullptr to a pointer is so that we can check later if it is not pointing to anything ? or are there any other use for it ?

        • Alex

          Yes, that's right. We use nullptr as a way to say, "this pointer isn't pointing to anything right now". That way, we can determine whether the pointer is pointing to something or not via a simple if statement.

          The other (related) use for nullptr is to pass a null value into a pointer function parameter.

          • Hussain

            Amazing lessons Alex, Thanks a million 😉

            I was told that one bad use of pointers is to make pointers that point to nothing (AKA, dangling pointers). From above, I have the feeling that I was misinformed in the past!

            Would you kindly give example on uses we want to pass null value into a pointer function parameter?

            Also, is it true that null as an argument isn't as ()?

            Thanks in advance =)

            • Alex

              Let's be careful what we mean by "nothing". Null pointers and dangling pointers are not the same thing.

              A null pointer points to "nothing" (address 0). That is okay, because "nothing" is an acceptable known value that we can test for and work around.
              A dangling pointer points to a valid memory address, but not one that has been allocated for your application's use. These are he pointers that will get you in trouble, because there's no way to distinguish a dangling pointer from a valid one.

              I added an academic example of passing a nullptr to a function in the lesson. While this isn't particularly useful, it does show the mechanics. As for useful examples, we'll see some of those when we get into classes and object-oriented programming (in particular, we use a special type of function called a constructor to initialize our classes -- if our class contains a pointer and we want to initialize it to a null value, we'd pass in a null value).

              > Also, is it true that null as an argument isn’t as ()?

              null (0 or nullptr) is an explicit literal value, whereas () is an empty argument. They are definitely not the same thing -- one is an argument, one is the lack of an argument.

  • Jim

    At the beginning of this lesson you introduced a null pointer, int *ptr(0); which was changed to int *ptr = nullptr
    by C++11. I still like the former!

    Was this done since int*prt(5) and int *prt = 5 are both improper syntax. Since you can not assign a literal to a pointer variable?

    • Alex

      It was done mainly to help disambiguate whether a literal 0 was intended as an integer or null pointer. If you like the old-style, it will certainly continue to be supported.

  • Typo in the second code example:

    in 4th line, "an double" should be "a double".

  • csvan

    I believe there is an error in the last example in the section "the null pointer" here: did you not mean to dereference the pointer inside the if-condition, in order to check wether or not it points to anything? Right now it is written without a dereference operator.

    Keep coding. Use it for good 🙂

    • baldo

      The if (pnPtr) test to see if the pointer is null. If it is a null pointer then the address it is pointing is 0 (false). If the pointer is allocated (not null) then pnPtr points to a address != 0 (which means true).

Leave a Comment

Put all code inside code tags: [code]your code here[/code]