dwaach wrote:
Hi,
I am trying to compile the following program,
#include <iostream>
using namespace std;
typedef char* CHAR;
typedef const CHAR CCHAR;
void test(CCHAR pp)
{
cout<<"hello"<<endl;
}
void main()
See
http://www.parashift.com/c++-faq-lit....html#faq-29.3
>
{
const char* myChar = "tt";
test(myChar);
}
Output:
error: 'test' : cannot convert parameter 1 from 'const char *' to 'char
*const '
Conversion loses qualifiers
Why ?
When you add const to CCHAR it makes the *pointer* const, not the
pointee. Doing substitution back in for your typedefs yields:
void test(CCHAR) = void test(const CHAR)
= void test(CHAR const)
= void test(char* const) != void test(const char*)
Compare this example for more on this distinction:
struct S
{
char *p;
};
void Foo( S& s, const S& cs )
{
char c = 'c';
*s.p = 'a'; // Ok: non-const
s.p = &c; // Ok: non-const
*cs.p = 'a'; // Ok: pointee is non-const
cs.p = &c; // Error: pointer is const!
}
The reason for the error is that constness is not deep. It is applied
to the pointer in [cs], not the pointee of that pointer. Your example
is similar since it applies const to the pointer, not the pointee.
How to resolve this ?
First, call your pointer something other than the name of the type in
all caps. Try this:
#include <iostream>
using namespace std;
typedef char* PCHAR;
typedef const char* PCCHAR;
void test( PCCHAR pp)
{
cout<<"hello"<<endl;
}
int main()
{
const char* const s = "tt";
test(s);
return 0;
}
Cheers! --M