In this post we talk a little bit about the constant pointers and pointer to a constant and the difference between them.
In C programming, pointer is a crucial concept and it is always good to have a clear understanding of the fundamentals.
Constant pointer as the name indicates is a pointer whose value can not be changed. In another way, once a pointer is initialized with an address of a variable, it can not point to any other variable further. We can also say it is a read-only pointer. For example, take a look the following code snippet.
int var1 = 1, var2 = 2;
int * const pVar = &var1; //constant pointer to an integer
pVar = &var2; //Incorrect, gives a compilation error
We have declared two variables var1, and var2. A constant pointer pVar is initialized to point to var1. In the next statement we are trying to point pVar to var2 which is incorrect and gives a compilation error as follows.
[Error] assignment of read-only variable ‘pVar1’
A constant pointer is useless if we don’t initialize it with any address. The compiler gives no error in this case, but that pointer is useless because it can not point to any object further.
int count = 10;
int * const pCount;//Valid code;no compiler error
pCount = &count; //Invalid; compiler error
Pointer to constant:
A pointer to a constant object. This means that we can not modify the object addressed by this pointer. But we can always read the object via this pointer and also we can make this pointer to address another object. To understand this, let us look at the following code snippet.
int var = 1, other = 2;
const int *pVar =&var; //pointer to a constant
*pVar = 10;//error:assignment of read-only location’*pVar1′
printf(“%d”, *pVar); // Valid; we can always read the value
pVar = &other; //valid
We can also create a constant pointer to a constant with the following code. Through this pointer we can not change the value, and we can not make it point to any other object.
int var = 100, other = 200;
const int * const pVar = &var;//constant pointer to a constant
*pVar = 10;//Error:assignment of read-only location’*pVar1′
pVar = &other; //Invalid; compiler error
other = var / 10; //valid; we can read the value