• Advertisement
Sign in to follow this  

Quick question

This topic is 2634 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This code :

const char *foo(){
const char*p = "test";
return p;
}
int main(){
char *p = foo();
cout << p;
}


in the foo(), does it return a copy of p? I'm having brainfart. Is foo() a legal?

Share this post


Link to post
Share on other sites
Advertisement
foo in itself is just fine, as the storage duration of string literals is for the lifetime of the program.

The use of foo in main however, is not fine. It tries to assign a pointer-to-const-char to a pointer-to-char, which is not legal. The other way around would be fine, assigning from pointer-to-char to pointer-to-const-char.

You may be confused by the legacy rules that you may assign a string literal to a pointer-to-char assuming you do not attempt to modify the contents of the literal, due to APIs from the days where there were no const.

Share this post


Link to post
Share on other sites
Or you could simply just use std::string as I see no point really to use const char* for anything.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement