const pointer and pointer to const code example

Example 1: pointer to constant

#include<iostream>

int main()
{	
	int number_1{100};
    int number_2 {200};
    
    //the data(value) pointed by the pointer is constant 
	const int *some_ptr {&number_1};
    *some_ptr = 300 ; //Error
    *some_ptr = &number_2 ; // ok => the aderss is different 
  
  	//the adress pointed by the pointer is constant 
  	int *const some_ptr {&number_1} ;
  	some_ptr = &number_2 //error => the adress of the pointer is constant 
    *some_ptr = 123 // ok 
    
    // the adress and the data is constant 
   	const int const *some_ptr{&number_1};
  	*some_ptr = 32; // error
	some_ptr = &number_2; // error  
    
    return 0;
}

Example 2: pointer to constant

//the data(value) pointed by the pointer is constant 
	const int *some_ptr {&number_1};
//the adress pointed by the pointer is constant 
  	int *const some_ptr {&number1} ;

Tags:

Cpp Example