C constant pointers
What is Constant Pointers [ Const Pointer ] in C Programming :
- As name suggests , Constant Pointers Cannot be modified .
- Modification in Integer to which it Points to is Allowed
- Modification made in Pointer is Not Allowed
Syntax Declaration :
data_type * const Pointer_name = Initial_Address;
Sample Code Snippet :
int num = 20; int * const ptr = &num ; // Declare Constant Pointer *ptr = 20 ; // Valid Statement ptr ++ ; // Invalid Statement
Explanation :
- In the Diagram Shown The at 2001 we have Store the value 15 .
- Constant Pointer is Pointer to that Variable [Pointer Stores address 2001]
- We cannot Change the Address stored in Pointer Variable i.e 2001 is fixed
- But we can Change the Value at 2001 i.e we can change value 15 to 20
Example 1: Illustrate const pointer in C
#include<stdio.h> int main() { int num[2] = {10,20}; int* const ptr = &num[0]; printf("%d",*ptr); return(0); }
Output :
10
Explanation :
int* const ptr = &num[0];
We must initialize const pointer at the time of declaration. Otherwise it will cause error.
int* const ptr; ptr = &num[0];
above statements will cause error.
Example 2 : We cannot change address stored inside Pointer
#include<stdio.h> int main() { int num[2] = {10,20}; int* const ptr = &num[0]; ptr++; printf("%d",*ptr); return(0); }
Output :
Example 3 : We can change value stored at address.
#include<stdio.h> int main() { int num[2] = {10,20}; int* const ptr = &num[0]; *ptr = 30; printf("%d",*ptr); return(0); }
Output :
30
Summary
We can DO following operations -
- Assigning Value at Address
- Printing Address or Value
- Assigning Address at the time of declaration.
We Can’t DO following operations on const pointer -
- Adding Integer to const Pointer
- Subtracting Integer to const Pointer.
- Any operation that can change address of pointer.