const pointer code example

Example 1: const pointer c++

int *p;										// pointer to int
const int *p == int const *p;				// pointer to const int
int * const p;								// const pointer to int
const int * const p == int const * const p;	// const pointer to const int

Example 2: 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 3: 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