top of page

constant pointer and pointer to constant in C++


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

Couldn’t Load Comments
It looks like there was a technical problem. Try reconnecting or refreshing the page.
bottom of page