The Null Pointer

A reference must always belong to some variable. The line int& r; ends with the error declaration of reference variable 'r' requires an initializer (a reference needs a starting value). But a pointer doesn't have to point anywhere. That's what the value nullptr, the null pointer, is for:

int* currentPlayer = nullptr;

It's useful when "nothing" is one of the options. For example, in a game, the pointer currentPlayer points to the score of the player whose turn it is, and when the game ends, it's nobody's turn. You can also redirect a pointer to another variable, which a reference can't do: a reference always belongs to the variable it was created with.

#include <iostream>

int main() {
    int anna = 0;
    int peter = 0;

    int* currentPlayer = &anna;
    *currentPlayer = *currentPlayer + 5;

    currentPlayer = &peter;
    *currentPlayer = *currentPlayer + 3;

    currentPlayer = nullptr;

    std::cout << "Anna: " << anna << ", Peter: " << peter << std::endl;
    if (currentPlayer == nullptr) {
        std::cout << "Game over" << std::endl;
    }
    return 0;
}

This prints:

Anna: 5, Peter: 3
Game over

Notice the difference: currentPlayer = &peter; without the asterisk changes where the pointer points. *currentPlayer = *currentPlayer + 3; with the asterisk changes the variable it points to.

Reading or writing through nullptr is a bug, because there's no variable there. On your computer, the program usually crashes, and the terminal shows Segmentation fault. Here in the browser, it may stop with the error RuntimeError: unreachable, or even carry on with nonsense values. So when a pointer can be nullptr, always check it before you use it:

if (currentPlayer != nullptr) {
    std::cout << *currentPlayer << std::endl;
} else {
    std::cout << "Nobody's turn" << std::endl;
}

A pointer that you don't give a value (int* p;) holds a random address, just like an uninitialized variable holds garbage. So always set a pointer right away: to the address of a variable, or to nullptr.

Instructions

The program prints Points: 12 and then stops with an error, because the second time, printPoints gets nullptr and reads through it. Add a check to the function: when points is nullptr, the function prints Nobody's turn, otherwise it prints the points as before. The program then prints Points: 12 and then Nobody's turn.

It's Peter's turn. At the end of main (before return 0;), add a variable peter with the value 7, redirect the pointer currentPlayer to it and call printPoints(currentPlayer) again. The program prints Points: 12, Nobody's turn and Points: 7.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

8/10