In C/C++, the placement of the const
keyword in pointer declarations determines whether the data being pointed to, the pointer itself, or both are constant. Here’s a detailed breakdown with examples:
1. const int*
(Pointer to Constant Data)
- Data is read-only, but the pointer can be reassigned.
- Syntax variations:
const int*
,int const*
(both are equivalent). - Example:
int a = 10, b = 20;
const int* ptr = &a; // Pointer to constant data
// *ptr = 15; // Error: Data is read-only
ptr = &b; // Valid: Pointer can be reassigned
- Use Case: Pass data to a function without allowing modification.
2. int* const
(Constant Pointer to Mutable Data)
- Pointer is fixed, but the data can be modified.
- Example:
int a = 10, b = 20;
int* const ptr = &a; // Constant pointer to mutable data
*ptr = 15; // Valid: Data is writable
// ptr = &b; // Error: Pointer is read-only
- Use Case: Hardware registers or fixed memory locations.
3. const int* const
(Constant Pointer to Constant Data)
- Both the pointer and data are read-only.
- Example:
int a = 10, b = 20;
const int* const ptr = &a; // Constant pointer to constant data
// *ptr = 15; // Error: Data is read-only
// ptr = &b; // Error: Pointer is read-only
- Use Case: Immutable data with a fixed location (e.g., lookup tables).
Key Rules
const
applies to the left of*
(unless it’s the first token, then it applies to the right).- Use
const
to enforce immutability and prevent accidental modifications.
Visual Summary
Declaration | Data Modifiable? | Pointer Modifiable? | Example |
---|---|---|---|
const int* | ❌ | ✅ | const int* ptr = &var; |
int* const | ✅ | ❌ | int* const ptr = &var; |
const int* const | ❌ | ❌ | const int* const ptr = &var; |
Advanced Scenarios
Pointer to Pointer
const int** ptr; // Pointer to a pointer to const data
int* const* ptr; // Pointer to a constant pointer to data
int** const ptr; // Constant pointer to a pointer to data
Function Parameters
void print_data(const int* data); // Data cannot be modified
void setup_hardware(int* const reg); // Pointer is fixed, data can change
Common Pitfalls
- Accidental Casting: Removing
const
via casting (e.g.,const_cast
) can lead to undefined behavior. - Ambiguity:
int const*
andconst int*
are equivalent, but consistency improves readability.
By mastering these distinctions, you can write safer, more predictable code in C/C++.