0
char *a= "ABC";

"ABC" string is of const char* type. How can its address be assigned to a char* pointer? Shouldn't it be an error?

pmg
  • 106,608
  • 13
  • 126
  • 198
Yogesh Mittal
  • 187
  • 2
  • 12

2 Answers2

3
char *a = "ABC";

"ABC" is of type char [4] in C while it is of type const char [4] in C++.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • Are you sure it is true in C99 and in C11 ? – Basile Starynkevitch Sep 06 '14 at 19:22
  • @BasileStarynkevitch yes – ouah Sep 06 '14 at 19:23
  • @BasileStarynkevitch: That's the only kind of constant literal which is not `const`-modified... – Deduplicator Sep 06 '14 at 19:24
  • I can't recall any different situation while modifying such string literal than segfault. So, "ABC" is of type char, but it is stored in read-only memory? That would make sense. – macfij Sep 06 '14 at 19:32
  • 1
    @mac: string literals can be pooled and may be stored in read-only memory, if such exists, just like and together with constant compound-literals. Their type is still not `const`-qualified in C, nor in C++03 and earlier (later versions fixed that, as heralded by it being deprecated then). There is no guarantee either happens, and there's no guarantee there is any read-only memory. – Deduplicator Sep 06 '14 at 19:35
2

String literals in C have types of non-const arrays. From the C Standard (6.4.5 String literals):

The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence.

Though string literals in C have types of non-const arrays they shall not be modified.

If the program attempts to modify such an array, the behavior is undefined.

In this connection consider for example the declaration of standard C function strchr:)

char *strchr(const char *s, int c);

The function returns a pointer to the same string that as the parameter is defined with the qualifier const.

In C++ string literals have types of constant characters arrays.

From the C++ Standard

8 Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335