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 value2. 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 addressAs 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyRead 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
1Pointer Fundamentals
Introduction to PointersDeclaration & InitializationArithmetic - AssignmentArithmetic - OperationsConst PointersPointers & Arrays2Pointers & References
Pointers as ParametersReferences - &References as ParametersPointers vs References