All about ‘const’ with pointers !

Question: What is the difference between the following pointer declarations ?

const int *ptr;

int const *ptr;

int *const ptr;

const int *const ptr;

Answer: Let me explain each with an example program.

First: 

int main( )

{

int a = 6;

const int *ptr;  // The value to which the pointer is pointing is read-only.

ptr = &a;

*p = 7; //Trouble is here.

}

Output:

simple.c: error: read-only variable is not assignable

        *p = 7;

Second: 

int main( )

{

int a = 6;

int const *ptr;  // The value to which the pointer is pointing is read-only. Same as first.

ptr = &a;

*p = 7;  //Trouble is here.

}

Output:

simple.c: error: read-only variable is not assignable

        *p = 7;

Third: 

int main( )

{

int a = 6;

int b = 7;

int * const ptr = &a;  // ‘ptr’ cannot point to some other variable. The pointer itself is read-only.

*ptr = 8;

ptr = &b; //Trouble is here.

}

Output:

simple.c: error: read-only variable is not assignable

        p = &b;

Fourth:

int main( )

{

int a = 6;

int b = 7;

const int * const ptr = &a;  // pointer and its value – both are constant.

*ptr = 8;   //Trouble is here.

ptr = &b; //Trouble is here.

}

Output:

simple.c: error: read-only variable is not assignable

        *p = 7;

        ~~ ^

simple.c: error: read-only variable is not assignable

        p = &b;

Author Information:

Subhash.K.U, Principal Mentor, Subhash Embedded Classes,Bangalore.

VIEW SUBHASH’s PROFILE

SUBHASH LOVES TO TEACH ! CLICK HERE !

No Comment

You can post first response comment.

Leave A Comment

Please enter your name. Please enter an valid email address. Please enter a message.