Whey we cannot Convert pointer to a character ->TO-> a reference to a pointer to a constant character
I am interested in knowing the reason of syntax error when we call foo_ptr. When foo_char is allowed why not foo_ptr.
[Update 1.] I would be happy in knowing the reason that foo_char() is working, why foo_ptr() is not working .. What happens when pointer come in the picture.
[Update 2.]
Didnt work in Dev C++ compiler version 4.9.9.2 too ..
//code
//OS : Win XP
//Env: VC++ 2008
//NOT ALLOWED
void foo_ptr(const char * & ptr) //reference to a pointer to a constant character
{
return;
}
//allowed
void foo_char(const char & p_Char) //reference to a constant character
{
return;
}
int main()
{
char ch = 'd';
char *ptr = "anu";
foo_char(ch);
foo_ptr(ptr); //NOT ALLOWED syntax error, vc++, 2008
return 0;
}
Revised with more examples:
Raymond Chen provides the correct answer. By passing a non const pointer (
char *) as reference parameter of a const pointer (foo_ptr(const char * ¶m)) you risk returning a const pointer type (const char *) and the compiler won’t allow you to do that.Here’s Raymond Chen‘s example of that, but I tried to explain how things would go wrong if it compiled by adding additional comments and code:
But if you change your parameter so you can’t affect the value that the pointer points to then the compiler will let you past in a non-const because there is no chance a const valued pointer is returned.
By placing the keyword
constAFTER the*in your parameter deceleration you do just that. That means change:to
and your compiler will be happy.
Now you would not be able to do something like
ptr = "readonlystring"in the above example because that would never compile now. Based on your question that should be OK because you would not be able to do the assignment to aconst char &in your original example.