POINTERS weds CONSTANTS |
¡Hola,
This post describes one of the confusing topic in C/C++ . Relationship between Pointers and Constants.
Before going to details first of all I would like to brief some basics:
1) Reference & Pointer
The address that locates a variable within memory is called "reference" to that variable. Remember "&" you see all around your C/C++ project :D . Yes!!! its the same.
So, what is pointer :O !!!!
Pointer is a variable that stores the reference to a variable. In other word a pointer points to a variable whose reference it stores.
int i = 10;
int *ptr; // pointer
ptr = & i;
/* ---------
here ptr is pointer
and &i is the reference of i (in layman language address of i)What the hell is "*""*" is called the Dereference operator (*)
* can give you the value from address.
so if
int j = *ptr;
then j == 10 is true;
*/
2) Constant
As the name says constants are entities that don't change its value through out the code.
syntax:
const int i = 10;
or int const i = 10;
both are same ;)
POINTERS (hubby)" engaged to" CONSTANTS (wife)
There are three types of relationship between constants and pointers.
1) Pointer to Constant
Here the pointer cannot change the value of variable whose address it stores. But can change the address it is storing. (Husbands are not faithful !!!! :O they can have someone else in there heart :P and they can't change wife's nature :D)
eg:
int i = 10;
int j = 20;
const int *ptr = &i; // int const *ptr = &i; !!! is also valid :O :P
*ptr = 100; // invalid : assignment of read-only variable ‘ptr’
ptr = &j ; // valid
2) Constant pointer to variable
Here the pointer can change the value of variable whose address it stores. But cannot change the address it is storing. (Husbands are faithful and are smart enough to change wife's nature :O)
eg:
int i = 10;
int j = 20;
int *const ptr = &i;
*ptr = 100; // valid
ptr = &j ; // invalid : assignment of read-only variable ‘ptr’
3) Constant pointer to constant
Here the pointer neither change the value of variable whose address it stores. Nor it can change the address it is storing. (Husbands are faithful and helpless :D :P)
eg:
int i = 10;
int j = 20;
const int *const ptr = &i;
*ptr = 100; // invalid : assignment of read-only variable ‘ptr’
ptr = &j ; // invalid : assignment of read-only variable ‘ptr’
Up Qualification & Down Qualification
int i = 10;
const int j = 20;
int * ptr1;
const int *ptr2;
ptr1 = &i; // valid
ptr1= &j; // invalid: called down qualification in C/C++
ptr2 = &j; // valid
ptr2= &i; // valid : called up qualification in C/C++
Summary
int i = 10;
int j = 20;
int* ptr0;
const int* ptr1 = &i; // int const * ptr1;
int *const ptr2 = &i;
const int *const ptr3= &i;
*ptr1 = j; // invalid
ptr1 = &j ; //valid
*ptr2 = j; //valid
ptr2 = &j; // invalid
*ptr3 = j; //invalid
ptr3 = &j; // invalid
ptr1= &pp; // valid : up qualification
ptr0 = &pp; // invalid : down qualification