Understanding Reference and Pointer Types

Const Pointers and Pointers to Const

What is the difference between a const pointer and a pointer to const?

Abstract art representing computer programming

The placement of const in a pointer declaration can be confusing, but it's important to understand the difference:

  1. A pointer to const (e.g., const int*) is a pointer that points to a const value. You cannot change the value that the pointer points to, but you can change the pointer itself to point to another value.
  2. A const pointer (e.g., int* const) is a pointer that cannot be changed to point to another value. However, the value that the pointer points to can be changed.

Here's an example:

int main() {
  int x = 10;
  int y = 20;

  const int* ptr1 = &x;
  // Error: cannot change value through ptr1
  *ptr1 = 30; 
  // Okay: can change to point to another value
  ptr1 = &y;

  int* const ptr2 = &x;
  // Okay: can change value through ptr2
  *ptr2 = 30;
  // Error: cannot change to point to another value
  ptr2 = &y; 
}

You can also have a const pointer to a const value (e.g., const int* const), which means that neither the pointer nor the value it points to can be changed.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved