Frequently Asked C Language Interview Question & Answers

What is the difference between constant pointer and constant variable?

CONSTANT POINTERS AND POINTER TO CONSTANT

 

CONSTANT POINTERS

  • These type of pointers are the one which cannot change the address they are pointing to.

  • This means that suppose there is a pointer which points to a variable (or stores the address of that variable).

  • Now if we try to point the pointer to some other variable (or try to make the pointer store address of some other variable), then constant pointers are incapable of this.

  • A constant pointer is declared as: 'int *const ptr' ( the location of 'const' make the pointer 'ptr' as a constant pointer)

 

POINTER TO CONSTANT

  • These type of pointers are the one which cannot change the value they are pointing to.

  • This means they cannot change the value of the variable whose address they are holding.

  • A pointer to a constant is declared as : 'const int *ptr' (the location of 'const' makes the pointer 'ptr' as a pointer to constant.)

 

EXAMPLE ON CONSTANT POINTERS

  1. #include<stdio.h>

  2. #include <conio.h>

  3. int main(){

  4. int a[] = {10,11};

  5. int* const ptr = a;

  6.  

  7. *ptr = 11;

  8.  

  9. printf("\n value at ptr is : [%d]\n",*ptr);

  10. printf("\n Address pointed by ptr : [%p]\n",(unsigned int*)ptr);

  11.  

  12. ptr++;

  13. printf("\n Address pointed by ptr : [%p]\n",(unsigned int*)ptr);

  14.  

  15. getch();

  16. }

 

Output: when we compile the above code, the compiler complains increment of read-only variable ‘ptr’.

 

EXAMPLE ON POINTER TO CONSTANTS

  1. #include<stdio.h>

  2. #include <conio.h>

  3. int main(){

  4. int a = 10;

  5. const int* ptr = &a;

  6.  

  7.  

  8. printf("\n value at ptr is : [%d]\n",*ptr);

  9. printf("\n Address pointed by ptr : [%p]\n",(unsigned int*)ptr);

  10.  

  11. *ptr = 11;

  12.  

  13. getch();

  14. }

Output: when the above code is compiled, the compiler complains assignment of read-only location ‘*ptr’