Difference Between Const Ptr And Ptr to Const

This question becomes sometimes favorite in C interview. It very easy to confuse and play around in question that goes like this. What is difference between pointer to constant and constant pointer? How do you declare Constant Pointers and Pointers to Constants? If you could able to answer these questions then next question will be what is use of const ptr and ptr to const?

Basically when we use Const keyword in C language. Well, when we have some value in program that is not going to change then we make use of Const keyword. This tell compiler that the value of the variable is not going to change at any point of time during run-time, So this kind of variables are stored at initialized data segment of memory. To be precise Const type of variable values will be stored in initialized read-only area and the address of variable will be stored in initialized read-write area of data segment.

Well as it looks confusing but its easy to remember and play around all sort of questions. Here is the trick to remember and answer these confusing questions.

When someone says, pointer to constant char then start writing in reverse while coding, So in this case I will put first pointer – ie ‘* myptr’ then look at requirement what is const here, it is char. So it will be like – ‘ char * myptr’ and in the end put ‘const’ type. So to declare pointer to const char

const char * myptr;

Now when some says, declare constant pointer to char then, it will be,

char * const myptr;

The trick here is where to put ‘const’ keyword decides the declaration.  In first case ie pointer to a constant character, one cannot use ‘myptr’ pointer to change the value of char, ie value being pointed to.

    char temp = 'x';
    const char * myptr = &temp;
    *myptr = 'J'; // error -  assignment of read-only location *myptr

In case of constant pointer to a character. The location stored in the pointer cannot change. You cannot change where this pointer points.

    char temp = 'x';
    char temp1='y'

    char  *  const myptr = &temp;
    myptr = &temp1; // error -  assignment of read-only location *myptr

Now the most famous question in field of embedded systems. If you are working in embedded system and working on firmware ie programming for microcontrollers then this will be for you, declare const pointer to constant char and what is use of such variable. ie both value pointed by pointer is constant and pointer itself is constant. The answer is very simple its use is to declare program status word. Its special register which contains CPU status and all, simply its status flag of your microcontroller. So this kind of status registers are read only by value as well as by location.

const char * const myptr = &status;

So next time interview question comes on about const pointer remember me. Good Luck.



Number of View :5299
  1. No comments yet.

Content Protected Using Blog Protector By: PcDrome.