Menu
Coddy logo textTech

Const Pointers

Lesson 5 of 14 in Coddy's C++ Pointers course.

A constant pointer is one whose value (the memory address it points to) cannot be changed after initialization. However, the value at the memory location it points to can be modified. There are two primary types of pointers when we mention constant pointers

  • Pointer to a constant - points to a constant value
  • Constant pointer - constantly points to a value

So, what's the difference


1. Pointer to a Constant

This type of pointer points to a constant value. The value cannot be modified through the pointer. So this means that it's a normal pointer it just points to a constant value, with this pointer the address that it points to can be changed.

int a = 5, b = 10;
// Pointer to a constant int
int const * ptr = &a;
 
// This is allowed:
ptr = &b; // Changing address
 
// This is not allowed:
*ptr = 10; // Trying to change a constant value

2. Constant Pointer

A constant pointer points to a non-constant value, but the pointer itself cannot be changed to point to a different address, it has a constant pointing address

int a = 5, b = 10;
// Constant pointer to an int
int * const ptr = &a;

// This is allowed:
*ptr = 10; // Changing non-const value

// This is not allowed:
ptr = &b; // Trying to change a constant address

As you can see, the const keyword is placed before the * for a pointer to a constant value and after the * for a constant pointer to a non-constant value. We could also combine them and have a constant pointer to a constant value, we would do it with two const keywords, before, and after the asterisk, but we would rarely need that situation

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Read two numbers from input, create a constant pointer constPtr and a pointer to constant ptrConst, initialize constPtr to point to the first number and then change its value to the second number, and set the address of ptrConst to point to the second number

Try it yourself

#include <iostream>

using namespace std;

int main() {

    // Enter code here


    // DO NOT CHANGE THE CODE BELOW
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    if(&a == constPtr)
        cout << "&a == constPtr" << endl;
    if(&b == ptrConst)
        cout << "&b == ptrConst" << endl;

    return 0;
}

All lessons in C++ Pointers