Let us look at the following program:
File: const1.c
#include<stdio.h>
int main(void)
{
int var1 = 0, var2 = 20;
//Constant Pointer
//The ptr is a constant . I cannot change the value of the pointer.
int* const ptr1 = &var1;
//Can't do this
//ptr1 = &var2;
//or this
//int *const ptr2 ;
//Can change the value of what the pointer points to
*ptr1 = 100 ;
printf("%d\n\n", *ptr1);
return 0;
}
We have the concept of a constant pointer. It is defined as:
int* const ptr1
What this is saying is that the variable "ptr1" is a constant and we cannot change it's value but we can change the value of what it's pointing to.
So we cannot do this:
ptr1 = &var2
but we can do
*ptr1 = 100
Let us build a RAM diagram:
RAM
var1 10 0 -->But we can change this value
ptr1 100 10 --> Can't change this value
We can't do :
int* const ptr2 ;
Since the variable ptr2 is a constant we must assign a value to it once we define it. We can also have the other case of having the ability to change a pointer but not change the value of what it is pointing to.
File: const3.cpp
#include<stdio.h>
int main(void)
{
int var1 = 0, var2 = 20;
const int* ptr1 = &var1;
//Not allowed
//*ptr1 = 1;
//Allowed
ptr1 = &var2 ;
printf("%d\n", *ptr1) ;
return 0;
}
The const is to the left of the pointer. This means the variable "ptr1" can be changed but the contents cannot be changed. Finally we have the case where the pointer or what the pointer points to cannot be changed.
File: const4.cpp
#include<stdio.h>
int main(void)
{
int var1 = 0, var2 = 20;
const int* const ptr1 = &var1;
//Not allowed
//*ptr1 = 1;
// Not Allowed
// ptr1 = &var2 ;
return 0;
}
We cannot change the value of what the pointer points to :
*ptr1 = 1
and we cannot change the value of the pointer:
ptr1 = &var2
Constant pointers are usually used in arguments to functions when we do not want the function to change the original value of what the pointer points to.
Ex: "const5.cpp"
#include<stdio.h>
#include<iostream>
using namespace std ;
void function1( const char* str1 )
{
cout << str1 << endl ;
*str1 = "Something Else." ;
}
int main(void)
{
char buffer[] = "Testing" ;
function1( buffer ) ;
return 0;
}
Output:
const5.cpp: In function ‘void function1(const char*)’:
const5.cpp:9:13: error: assignment of read-only location ‘* str1’
*str1 = "Something Else." ;
^~~~~~~~~~~~~~~~~
const5.cpp:9:13: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]