Why char * s = "hello"; allowed?

char *s = "hello";

The above code allocates 6 bytes in the read-only section of the program (I forgot the section name) to save the line hello. It is then sinitialized to indicate the first character of the string hello. Changing a string "hello"is undefined behavior. Moreover, "hello"in itself is constant. The program does not have permission to change the read-only section.

I am using MS VC ++ 2010 Express. My question is, why does the compiler allow s, which is char *, to point to a constant string? Should there be a compiler error? Shouldn't the compiler use const char *s = "hello";instead char *s = "hello";?

Thank.

+5
source share
2 answers

In C, "hello" has a type char[]. This is not C ++. See this question .

+5
source

This precedes the time a classifier constwas introduced in C. The body of C standards is very conservative with respect to existing code. Any improvement of the language should be carried out in such a way that it does not violate the existing relevant code that was written for the previous version of the standard.

If such things lead to undesirable complications, the function then becomes obsolete and can change a few years after that.

, char[] char const[], , , , . char const* , .

: , , .

int main(void) {
  "hello"[0] = 'H';
  char * a = "hoho";
  a[0] = 'H';
}

gcc , . clang .

+2

All Articles