0

Using visual studio, I declared a pointer of type char * and assigned to it a string literal. I then hovered the mouse over the string literal and it displayed its type: (const char [4])"abc".

How is this allowed? it compiles without warnings or errors, whilst assigning to the pointer an array of type const char [] fails, for obvious reasons, with an error message:

a value of type "const char *" cannot be assigned to an entity of type "char *"

So, why is it allowed for string literals?

int main(void)
{
    char *p = "abc"; // no error here
    const char str[] = "abc";
    //p = str; This line generates an error
    return 0;
}
7
  • 1
    Which bit of the error message don't you understand? A const char * is not the same thing as a char *. Commented Oct 27, 2017 at 14:52
  • and assigned it to a string literal. no, you assigned to it. Commented Oct 27, 2017 at 14:52
  • You are not assigning a pointer to char to a string literal. Commented Oct 27, 2017 at 14:54
  • Which version of Visual Studio are you using? Commented Oct 27, 2017 at 15:07
  • 1
    @NeilButterworth The OP is asking why VS compiles that code without raising a warning nor that error Commented Oct 27, 2017 at 15:09

1 Answer 1

0

EDIT: answer updated to incorporate info from Story Teller's comment.

In the olden days, const didn't exist, and people wrote things like char* p = "abc" all the time. As long as the didn't then do something like p[0] = 'z', their program worked. To remain compatible with such code, some compilers allow string literals to be assigned to non-const pointers if you don't ask the compiler to be super-strict. If you take advantage of this feature, you still should not ACTUALLY modify the string.

Sign up to request clarification or add additional context in comments.

2 Comments

Um, no. String literals are const. The type of "abc" is const char[4], as the question says.
Story Teller: no fair removing your comment when I'm trying to cite you! :)