Explain: Converting 'char **' to 'const char **', Conversion loses qualifiers [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Implicit cast from char** to const char**
Given the following code:
void foo( const char ** buffer );
void bar()
{
char * buffer;
foo( &buffer );
}
Why is it that if the foo() function has a const char * parameter the compiler doesn't complain when passing in a char * variable into it? But when using char **, it cannot convert it to const char **? Does the compiler add any const qualifiers in the former case?
I've read section 4.4 of the C++ standard and it just confused me further.

Yes, you cannot implicitly convert from a T ** to a const T **, because the compiler can no longer guarantee that the const-ness won't be violated.
Consider the following code (borrowed from the C FAQ question on exactly this topic: Why can't I pass a char ** to a function which expects a const char **?):
const char c = 'x';
char *p1;
const char **p2 = &p1; // 3
*p2 = &c;
*p1 = 'X'; // 5
If the compiler allowed line 3, then line 5 would end up writing to a const object.

Consider:
char const someText[] = "abcd";
void
foo( char const** buffer )
{
*buffer = someText;
}
void
bar()
{
char* buffer;
foo( &buffer );
*buffer = 'x';
}
If this were legal, it would be possible to modify a const object
without an intervening const_cast. The conversion is forbidden
because it violates const-ness.

You are probably confusing the level of indirection the const applies to.
A char** can be described as pointer to a pointer to a character whereas a const char** can be described as pointer to a pointer to a constant character.
So when we write this differently, we have pointer to A (where A = pointer to character) and we have pointer to B (where B = pointer to a constant character).
Clearly now (I hope) A and B are distinct types, as such a pointer to A can not be assigned toa a pointer to B (and vice versa).

Related

C++ pointer passed by reference [duplicate]

This question already has answers here:
why no implicit conversion from pointer to reference to const pointer
(4 answers)
Closed 1 year ago.
The following code won't compile:
void function(const char*& i){
// do something
}
int main() {
char a = 'a';
char *p = &a;
function(p);
return 0;
}
Can someone explain to me why?
What is the code doing? the code in the main function is passing a normal pointer to char to a pointer to a constant char.
As far as I know, as long as the passed pointer does not get violated in the function, the call should be allowed.
the address and value of a normal pointer to char may be modified, so such a pointer cannot be violated if passed by reference to a function whose sole argument is a pointer to a constant char because such a pointer can only modify its address, and that does not violate the restrictions of a normal pointer to char.
Edit:
The reason it does not compile is because when char* is converted to const char*, it results in an rvalue of type const char*. in C++, a non-const reference cannot be attached to an rvalue.
So the solution is simply to make the reference constant by adding const to give the argument the type constant pointer ... to a constant.
void function(const char* const& i){
// do something
}
int main() {
char a = 'a';
char *p = &a;
function(p);
return 0;
}
what you're doing is no much different from
const char* function(){
return "const char*";
}
int main() {
char *p = function(); // not compile
}
It's obviously wrong to have a non-const char* point to a constant
re comment: it is obviously very different. the const char*& means "I will not modify the value of a pointer to char passed to me"
NO it does not means that (godbolt)
void function(const char*& i){
i = "const char*"; // compiles fine
}
int main() {
const char *p;
function(p);
}

why `int**` can't be casted to `const int**` [duplicate]

It is legal to convert a pointer-to-non-const to a pointer-to-const.
Then why isn't it legal to convert a pointer to pointer to non-const to a pointer to pointer to const?
E.g., why is the following code illegal:
char *s1 = 0;
const char *s2 = s1; // OK...
char *a[MAX]; // aka char **
const char **ps = a; // error!
From the standard:
const char c = 'c';
char* pc;
const char** pcc = &pc; // not allowed
*pcc = &c;
*pc = 'C'; // would allow to modify a const object
Ignoring your code and answering the principle of your question, see this entry from the comp.lang.c FAQ:
Why can't I pass a char ** to a function which expects a const char **?
The reason that you cannot assign a char ** value to a const char ** pointer is somewhat obscure. Given that the const qualifier exists at all, the compiler would like to help you keep your promises not to modify const values. That's why you can assign a char * to a const char *, but not the other way around: it's clearly safe to "add" const-ness to a simple pointer, but it would be dangerous to take it away. However, suppose you performed the following more complicated series of assignments:
const char c = 'x'; /* 1 */
char *p1; /* 2 */
const char **p2 = &p1; /* 3 */
*p2 = &c; /* 4 */
*p1 = 'X'; /* 5 */
In line 3, we assign a char ** to a const char **. (The compiler should complain.) In line 4, we assign a const char * to a const char *; this is clearly legal. In line 5, we modify what a char * points to--this is supposed to be legal. However, p1 ends up pointing to c, which is const. This came about in line 4, because *p2 was really p1. This was set up in line 3, which is an assignment of a form that is disallowed, and this is exactly why line 3 is disallowed.
And as your question is tagged C++ and not C, it even explains what const qualifiers to use instead:
(C++ has more complicated rules for assigning const-qualified pointers which let you make more kinds of assignments without incurring warnings, but still protect against inadvertent attempts to modify const values. C++ would still not allow assigning a char ** to a const char **, but it would let you get away with assigning a char ** to a const char * const *.)
Just since nobody has posted the solution, here:
char *s1 = 0;
const char *s2 = s1; // OK...
char *a[MAX]; // aka char **
const char * const*ps = a; // no error!
(http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17 for why)
The C++11 draft standard explains this in a note in section 4.4 which says:
[ Note: if a program could assign a pointer of type T** to a pointer
of type const T** (that is, if line #1 below were allowed), a program
could inadvertently modify a const object (as it is done on line #2).
For example,
int main() {
const char c = 'c';
char* pc;
const char** pcc = &pc; // #1: not allowed
*pcc = &c;
*pc = 'C'; // #2: modifies a const object
}
—end note ]
An interesting related question is Given int **p1 and const int **p2 is p1 == p2 well formed?.
Note the C++ FAQ also has an explanation for this but I like the explanation from the standard better.
The conforming text that goes with the note is as follows:
A conversion can add cv-qualifiers at levels other than the first in
multi-level pointers, subject to the following rules:56
Two pointer types T1 and T2 are similar if there exists a type T and
integer n > 0 such that:
T1 is cv1,0 pointer to cv1,1 pointer to · · · cv1,n−1 pointer to cv1,n
T
and
T2 is cv2,0 pointer to cv2,1 pointer to · · · cv2,n−1 pointer to cv2,n T
where each cvi,j is const, volatile, const volatile, or nothing. The
n-tuple of cv-qualifiers after the first in a pointer type, e.g.,
cv1,1, cv1,2, · · · , cv1,n in the pointer type T1, is called the
cv-qualification signature of the pointer type. An expression of type
T1 can be converted to type T2 if and only if the following conditions
are satisfied:
the pointer types are similar.
for every j > 0, if const is in cv1,j then const is in cv2,j , and similarly for volatile.
if the cv1,j and cv2,j are different, then const is in every cv2,k for 0 < k < j.
There are two rules here to note:
There are no implicit casts between T* and U* if T and U are different types.
You can cast T* to T const * implicitly. ("pointer to T" can be cast to "pointer to const T"). In C++ if T is also pointer then this rule can be applied to it as well (chaining).
So for example:
char** means: pointer to pointer to char.
And const char** means: pointer to pointer to const char.
Since pointer to char and pointer to const char are different types that don't differ only in const-ness, so the cast is not allowed. The correct type to cast to should be const pointer to char.
So to remain const correct, you must add the const keyword starting from the rightmost asterisk.
So char** can be cast to char * const * and can be cast to const char * const * too.
This chaining is C++ only. In C this chaining doesn't work, so in that language you cannot cast more than one levels of pointers const correctly.

error: invalid conversion from ‘char**’ to ‘const char**’ [-fpermissive] [duplicate]

It is legal to convert a pointer-to-non-const to a pointer-to-const.
Then why isn't it legal to convert a pointer to pointer to non-const to a pointer to pointer to const?
E.g., why is the following code illegal:
char *s1 = 0;
const char *s2 = s1; // OK...
char *a[MAX]; // aka char **
const char **ps = a; // error!
From the standard:
const char c = 'c';
char* pc;
const char** pcc = &pc; // not allowed
*pcc = &c;
*pc = 'C'; // would allow to modify a const object
Ignoring your code and answering the principle of your question, see this entry from the comp.lang.c FAQ:
Why can't I pass a char ** to a function which expects a const char **?
The reason that you cannot assign a char ** value to a const char ** pointer is somewhat obscure. Given that the const qualifier exists at all, the compiler would like to help you keep your promises not to modify const values. That's why you can assign a char * to a const char *, but not the other way around: it's clearly safe to "add" const-ness to a simple pointer, but it would be dangerous to take it away. However, suppose you performed the following more complicated series of assignments:
const char c = 'x'; /* 1 */
char *p1; /* 2 */
const char **p2 = &p1; /* 3 */
*p2 = &c; /* 4 */
*p1 = 'X'; /* 5 */
In line 3, we assign a char ** to a const char **. (The compiler should complain.) In line 4, we assign a const char * to a const char *; this is clearly legal. In line 5, we modify what a char * points to--this is supposed to be legal. However, p1 ends up pointing to c, which is const. This came about in line 4, because *p2 was really p1. This was set up in line 3, which is an assignment of a form that is disallowed, and this is exactly why line 3 is disallowed.
And as your question is tagged C++ and not C, it even explains what const qualifiers to use instead:
(C++ has more complicated rules for assigning const-qualified pointers which let you make more kinds of assignments without incurring warnings, but still protect against inadvertent attempts to modify const values. C++ would still not allow assigning a char ** to a const char **, but it would let you get away with assigning a char ** to a const char * const *.)
Just since nobody has posted the solution, here:
char *s1 = 0;
const char *s2 = s1; // OK...
char *a[MAX]; // aka char **
const char * const*ps = a; // no error!
(http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17 for why)
The C++11 draft standard explains this in a note in section 4.4 which says:
[ Note: if a program could assign a pointer of type T** to a pointer
of type const T** (that is, if line #1 below were allowed), a program
could inadvertently modify a const object (as it is done on line #2).
For example,
int main() {
const char c = 'c';
char* pc;
const char** pcc = &pc; // #1: not allowed
*pcc = &c;
*pc = 'C'; // #2: modifies a const object
}
—end note ]
An interesting related question is Given int **p1 and const int **p2 is p1 == p2 well formed?.
Note the C++ FAQ also has an explanation for this but I like the explanation from the standard better.
The conforming text that goes with the note is as follows:
A conversion can add cv-qualifiers at levels other than the first in
multi-level pointers, subject to the following rules:56
Two pointer types T1 and T2 are similar if there exists a type T and
integer n > 0 such that:
T1 is cv1,0 pointer to cv1,1 pointer to · · · cv1,n−1 pointer to cv1,n
T
and
T2 is cv2,0 pointer to cv2,1 pointer to · · · cv2,n−1 pointer to cv2,n T
where each cvi,j is const, volatile, const volatile, or nothing. The
n-tuple of cv-qualifiers after the first in a pointer type, e.g.,
cv1,1, cv1,2, · · · , cv1,n in the pointer type T1, is called the
cv-qualification signature of the pointer type. An expression of type
T1 can be converted to type T2 if and only if the following conditions
are satisfied:
the pointer types are similar.
for every j > 0, if const is in cv1,j then const is in cv2,j , and similarly for volatile.
if the cv1,j and cv2,j are different, then const is in every cv2,k for 0 < k < j.
There are two rules here to note:
There are no implicit casts between T* and U* if T and U are different types.
You can cast T* to T const * implicitly. ("pointer to T" can be cast to "pointer to const T"). In C++ if T is also pointer then this rule can be applied to it as well (chaining).
So for example:
char** means: pointer to pointer to char.
And const char** means: pointer to pointer to const char.
Since pointer to char and pointer to const char are different types that don't differ only in const-ness, so the cast is not allowed. The correct type to cast to should be const pointer to char.
So to remain const correct, you must add the const keyword starting from the rightmost asterisk.
So char** can be cast to char * const * and can be cast to const char * const * too.
This chaining is C++ only. In C this chaining doesn't work, so in that language you cannot cast more than one levels of pointers const correctly.

Weird behavior of pointer

When I compile the given code it doesn't produce any error or warnings. My question here is shouldn't the compiler produce error when compiling the following line *err = "Error message"; because we are dereferencing a pointer to pointer to constant char and assigning a string to it.
Is it allowable to assign anything inside a pointer anything other than address and exactly what is happening in this given scenario?
#include <stdio.h>
void set_error(const char**);
int main(int argc, const char* argv[])
{
const char* err;
set_error(&err);
printf("%s",err);
return 0;
}
void set_error(const char** err1)
{
*err1 = "Error message";
}
const char** err1
That's a pointer to a non-constant pointer to a constant object. Dereferencing it gives a non-constant pointer (to a constant object), which can be assigned to.
To prevent assigning to the const char*, that would also have to be const:
const char * const * err1
"Error message" is not a std::string. It's a const char[]. All string literals in C++ are const char[]. In C, they're char[].
Is it allowable to assign anything inside a pointer anything other than address and exactly what is happening in this given scenario?
You can assign pointer to a pointer. You think about pointer as an address, that's fine to understand concept, but do not mix it with data type. Data type is a pointer, not address. For example to assign address in memory to a pointer you need to cast it to a pointer:
char *pointer = reinterpret_cast<char *>( 0xA000000 );
You may ask how this would compile?
int array[10];
int *ptr = array;
That comes from C - array can be implicitly converted to a pointer to the first element. So it is pointer to pointer assignment again. Now about string literal with double quotes. It is an array as well:
const char str[] = "str";
const char str[] = { 's', 't', 'r', '\0' };
These 2 statements are pretty much the same. And as array can be implicitly converted to pointer to the first element it is fine to assign it to const char *

Assigning pointers to pointers with or without qualifiers [duplicate]

This question already has answers here:
constness and pointers to pointers
(4 answers)
Closed 9 years ago.
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?
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
cdecl really helps in cases like this.
const char** p2p2cc = declare p2p2cc as pointer to pointer to const char
and
const char * const * p2cp2cc = declare p2cp2cc as pointer to const pointer to const char
As you can see, the second version has the inner AND the outer pointer const, meaning it cannot modify either. The first version has the INNER pointer const and the outer non-const thereby breaking constnes.
On the other hand, this works:
char** const p = p2p2c;