Null pointer in C++

Level 3119 keystrokes

nullptr marks a pointer that points to nothing. The code checks for it before use, prints "Null pointer", then points ptr at x and dereferences it to print 10.

C++ code

// nullptr (C++11) is the type-safe null pointer, preferred over NULL or 0
1int* ptr = nullptr;
// Dereferencing a null pointer is undefined behavior, so check first
2if (ptr == nullptr) {
// ptr is null here, so this is printed
3 cout << "Null pointer" << endl;
4}
5int x = 10;
// Now ptr points to a real variable
6ptr = &x;
// Safe to dereference: prints 10
7cout << *ptr << endl;

Output

Null pointer
10
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 8
  • ;× 5
  • =× 5
  • "× 2
  • *× 2
  • (× 1
  • )× 1
  • {× 1
  • }× 1
  • &× 1

More C++ examples at level 3

← C++ typing practice