-->




const pointer in c++ with examples

Leave a Comment
What in const in C++?
Const which is short form of constant uses where we don't want to change or modify data. In programming const allow to set limit or control the code as you want. For example we pass some data to a function and want to ensure that function should not have rights to change it then const is used.

Lets discuss a scenario we have an array of size 10 and passes to a function which traverse to whole array and display its value. So to traverse completely, array size should be known in the function and it should not be modified so for good programming array size should be declare as const.


Different scenario with const pointers 

Making non constant pointer to non constant data
Its allows the full modified mode means both pointers and data can be changed or modified to each other by deference.
for example
int *iPtr, i=9;
iPtr=&9;


Making constant pointer to non constant data
int number=10;
const int *ciPtr=&number;

*ciPtr=20; allowed because number is not a const data

int number2=10;
ciPtr=&number2;  ERROR not allowed because ciPtr is constant 


Making constant pointer to constant data
const int number=10;
const *ciPtr=&number;

*ciPtr=20; ERROR ciPtr is pointing to a const value can't be changed

const int number2=10;
const *ciPtr=&number2;  ERROR ciPtr is const can't point to another address

If you have any confiusion about pointer basics read Learn pointer in c++ programming

0 comments:

Post a Comment