Juan Torres Juan Torres - 1 year ago 120
C++ Question

const int implicit conversion C++

i'd like to know if there is a sort of implicit conversion between variables when using a pointer to constant integer ,
for example , if i use an address of a variable type int or const int it accepts to store it ,
however if i use a normal pointer to int it doesn't allow storing the address of the const int type,why is this?, thanks in advance

int i=4;
const int ii=4;

//pointer to constant int
const int *pci=&i; //OK.
pci=ⅈ //OK.
int *pi=ⅈ //ERROR invalid conversion.

Answer Source

The first and second assignments initialize pci to constly point to an int or a const int.

So you might have one of two situations:

  • const int* which points to an int.

  • const int* which points to a const int.


Both cases are safe because you are only adding a constraint.

By doing:

int *pi=ⅈ

You make an int* point to a const int which means you remove a constraint.

Since removing a constraint might be risky, this requires you to use a const_cast.

int* pi = const_cast<int*>(&ii);

Note that forcibly removing the const modifier is something you should ask yourself twice if you really wanna do, since it also make the const modifier somewhat meaningless because you will be able to modify that "constant" address through the converted variable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download