C pointer to constant objects



Pointer to Constant Objects :

  • Pointer to a Constant Object is called as ‘Pointer to Constant Object’

Syntax :

const data-type *pointer_name ;

Example :

int n = 30 ;

const int ptr;
ptr = &n;

What does it means ?

  1. const int” means integer is constant.
  2. We cannot change value of the integer.
  3. Pointer to Such Object cannot be changed.
  4. We can change address of such pointer so that it will point to new memory location.

Following is illegal use of const int pointer –

*ptr = 20 ;

however we can use this legally –

ptr++ 

is valid in this Case !!!


Example 1 : How const int Pointer works ?

#include<stdio.h>

int main()
{
int num[2] = {10,20};
const int *ptr;

ptr = &num[0];

printf("%d",*ptr);

return(0);
}

Output:

10

Example 2 : Increment const int Pointer

#include<stdio.h>

int main()
{
int num[2] = {10,20};
const int *ptr;

ptr = &num[0];

ptr++;

printf("%d",*ptr);

return(0);
}

Output :

20

Example 3 : Assigning Value to const int pointer

#include<stdio.h>

int main()
{
int num[2] = {10,20};
const int *ptr;

ptr = &num[0];

*ptr = 30;

printf("%d",*ptr);

return(0);
}

Output :

Compile Error