Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I not allowed to assign a result of function returning const char* to char*, bt a string literal(constant) can be assigned to char*? [duplicate]

Tags:

c++

c

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?

like image 427
Malik Avatar asked Mar 12 '23 12:03

Malik


1 Answers

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.

like image 161
Bo Persson Avatar answered Apr 06 '23 22:04

Bo Persson