4

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?

Malik
  • 83
  • 3
  • 2
    A string literal is special. In particular, it is not a `const char*`. – molbdnilo Apr 26 '16 at 06:26
  • 7
    Is this C or C++? String literals are slightly different in the two different languages. – Some programmer dude Apr 26 '16 at 06:26
  • This is indeed an inconsistent behavior slightly remedied since c++11 in which case you will get a warning for the first assignment – Uri Brecher Apr 26 '16 at 06:27
  • 2
    Please delete either the C or the C++ tag. Answers will be different depending on language. – Lundin Apr 26 '16 at 06:28
  • 2
    ISO C++11 does not allow conversion from string literal to `char*`, so your "works fine" is situational at-best. – WhozCraig Apr 26 '16 at 06:28
  • string literals are immutable since they reside in the read-only portion of the memory. If you use a string literal like you have shown they ought to be const char*. – Sumit Trehan Apr 26 '16 at 06:36
  • **Neither is allowed**. Your compiler is just being forgiving in the *"works fine"* case. – Nawaz Apr 26 '16 at 06:40
  • The answer to "Why am I not allowed to assign a result of function returning const char* to char*?" is because `const`-qualification cannot be removed by implicit conversion. But it seems your real question is "Why does the line with the string literal compile?" , or "why does string literal behave differently to `const char *`". Suggest editing title to clarify – M.M Apr 26 '16 at 07:37
  • Please suggest the answers for C as well as for C++ . @joachim Pileborg – Malik Apr 26 '16 at 07:53
  • Why does the line with the string literal compile? considering " this is a const string one" is read only ie const @M.M – Malik Apr 26 '16 at 07:54
  • @Malik the question linked by Lundin explains that – M.M Apr 26 '16 at 07:55
  • Lets say the above code is in C , then writing d[3]='k' results in runtime error . why ? – Malik Apr 26 '16 at 08:15
  • Do you mean there is a difference in memory layout difference @molbdnilo . Can you explain the speciality of string literal . – Malik Apr 26 '16 at 08:34

1 Answers1

7

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.

Community
  • 1
  • 1
Bo Persson
  • 90,663
  • 31
  • 146
  • 203