Constant Pointers

In C Constant pointers can be applied to the declaration of any variable to specify that it value will not be changed.  And we can say that if a constant pointer is pointing to some variable then it cannot point to any other variable.

Syntax of Constant Pointer

*const ;

int*const ptr;

Let’s see the example of constant pointer

#include <stdio.h>  
int main()  
{  
    int a=1;  
    int b=2;  
    int *const ptr;  
    ptr=&a;  
    ptr=&b;  
    printf("Value of ptr is :%d",*ptr);  
    return 0;  
}

Output

Compilation failed due to following error(s).
main.c: In function 'main';
main.c:16:8 : error: assignment of read-only variable 'ptr'
      ptr=&a;
         ^

main.c:17:8 : error: assignment of read-only variable 'ptr'
      ptr=&b;
         ^

Pointer to Constant

Pointer through which the value of the variable that the pointer points can’t be changed.In this pointer to constant the address of these pointers can be changed but the value of the variable that the pointer points can’t be changed.

Syntax of pointer to constant

const*

Declaration of a pointer to constant

const int*ptr;

Let’s see the example of pointer to constant

#include <stdio.h>  
int main()  
{  
    int a=100;  
    int b=200;  
    const int* ptr;  
    ptr=&a;  
    ptr=&b;  
    printf("Value of ptr is :%u",ptr);  
    return 0;  
}

Output

Value of ptr is : 247760772

Constant pointer to constant

In this constant pointer is the combination of the above two pointers.It can neither change the address of the variable to which is pointing nor it can change the value placed at this address.

Syntax of the Constant pointer to a constant

const<type of pointer>*const<name of the pointer>;

Declaration for constant pointer to a constant

const int*const ptr;

Let’s see the example of constant pointer to a constant

#include <stdio.h>  
int main()  
{  
    int a=10;  
    int b=90;  
    const int* const ptr=&a;  
   *ptr=12;  
    ptr=&b;  
    printf("Value of ptr is :%d",*ptr);  
    return 0;  
}

Output

Compilation failed due to following error(S).

main.c: In function 'main';
main.c:17:9 : error: assignment of read-only location '*ptr'
     *ptr=12;
         ^

main.c:18:6 : error: assignment of read-only variable 'ptr'
    ptr=&b;
       ^

Submit your review
1
2
3
4
5
Submit
     
Cancel

Create your own review

The Technical Funda
Average rating:  
 0 reviews