Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning pointers to pointers with or without qualifiers [duplicate]

Tags:

c++

c

pointers

c99

While this compiles:

char* p2c;
const char* p2cc = p2c; //fine

because lhs pointed type has all the qualifiers of rhs pointed type, this does not:

char** p2p2c;
const char** p2p2cc = p2p2c; //fail

but this does:

const char * const * p2cp2cc = p2p2c; //fine

Why exactly does this happen?

like image 724
emesx Avatar asked Sep 05 '13 13:09

emesx


1 Answers

This does not work:

char** p2p2c;
const char** p2p2cc = p2p2c; //fail

If that was allowed you would be allowed to break const-correctness:

const int k = 10;
int *p;
int **pp = &p;
int const **kpp = pp;     // Should this be allowed, if so:
*kpp = &k;                // fine, kpp promises not to change it
                          // yet this does p = &k;
                          // p made no such promise! this is a hidden const_cast!
*p = 5;

If the assignment was allowed, you would enable setting a non-const pointer (intermediate) to refer to a constant value, possibly causing undefined behavior in a non-obvious to see way. By disallowing that operation the type system is safer.

but this does:

const char * const * p2cp2cc = p2p2c; //fine

This is fine, since the intermediate pointer is fixed, it is impossible to reset the intermediate pointer to refer to a const object and break const-correctness

like image 79
David Rodríguez - dribeas Avatar answered Nov 01 '22 10:11

David Rodríguez - dribeas