In C, the const keyword can be used with pointers in two main ways, affecting either the pointer itself or the data it points to. Here’s how it works:
-
Pointer to Constant Data: When you declare a pointer to a constant type, it means that the data being pointed to cannot be modified through that pointer.
const int *ptr;In this case,
ptris a pointer to anintthat is constant. You can change the pointer to point to another integer, but you cannot change the value of the integer it points to throughptr.int a = 10; int b = 20; ptr = &a; // Valid // *ptr = 15; // Error: cannot modify the value pointed to by ptr ptr = &b; // Valid: ptr can point to another integer -
Constant Pointer: When you declare a constant pointer, it means that the pointer itself cannot be changed to point to another address, but the data it points to can be modified.
int *const ptr;In this case,
ptris a constant pointer to anint. You cannot change whereptrpoints, but you can change the value at that address.int a = 10; ptr = &a; // This must be done at the time of declaration *ptr = 15; // Valid: you can modify the value pointed to by ptr // ptr = &b; // Error: cannot change the address stored in ptr -
Constant Pointer to Constant Data: You can also combine both concepts, creating a constant pointer to constant data.
const int *const ptr;In this case, neither the pointer can be changed to point to another address, nor can the data it points to be modified.
int a = 10; ptr = &a; // This must be done at the time of declaration // *ptr = 15; // Error: cannot modify the value pointed to by ptr // ptr = &b; // Error: cannot change the address stored in ptr
Using const with pointers helps to enforce better coding practices by preventing unintended modifications to data and improving code safety.
