Why am I not allowed to assign the result of a function that returns const char * to char *, can a bt string literal (constant) be assigned to char *?

Function returning const char *cannot be assignedchar*

const char* func() {
    return "This is a const string two ";
}

but a char*constant string is assigned to 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 a contradiction?

+4
source share
1 answer

The string literal assignment char*inherits from C, where it is allowed long before C has a keyword const.

In later versions of the C ++ standard, this is deprecated . A modern compiler should warn you about this.

+7
source

All Articles