top of page

constant pointer and pointer to constant in C++

  • Writer: prashant raj
    prashant raj
  • May 2, 2021
  • 1 min read

Constant Pointer:

Constant pointer is a pointer that can not change the address it holding. Hence

once a constant pointer points to a variable then it can not point to any other variable.

Syntax:

int *const ptr = &variable

Example:

int main()
{
	int x = 10;
	int y = 20;
	int *const ptr = &x; //valid
	ptr = &y //invalid
} 

pointer to constant:

A pointer through which one can not change the value of variable it points.

These type of pointers can change the address they point but can not change the value

kept at these address.

Syntax:

const int *ptr;

example:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    int x = 20;
    int y = 40;
    const int *ptr;
    ptr = &x;
    cout<<*ptr<<endl;
    ptr = &y;
    cout<<*ptr<<endl;
    
    *ptr = 50;//invalid
}

Comments


Drop Me a Line, Let Me Know What You Think

Thanks for submitting!

© 2023 by Train of Thoughts. Proudly created with Wix.com

bottom of page