Function returning a const char *
cannot be assigned to char*
const char* func() {
return "This is a const string two ";
}
but char*
is assigned a constant string in main directly:
int main() {
char *d =" this is a const string one"; // works fine
char *e = func(); // error cannot convert from 'const char *' to 'char *'
return 1;
}
Why the contradiction?
Assigning a string literal to char*
is inherited from C, where this has been allowed since long before C had a const
keyword.
In later C++ standards, this has been deprecated. A modern compiler ought to warn you about that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With