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?

6
  • It's undefined behavior (see first example). Commented Sep 6, 2014 at 19:05
  • 2
    C is not as type-strict as C++ - that's the reason Commented Sep 6, 2014 at 19:07
  • Char is not a type in C. Do you mean char? Commented Sep 6, 2014 at 19:08
  • 4
    stackoverflow.com/questions/2245664/string-literals-in-c Commented Sep 6, 2014 at 19:11
  • 1
    No, "ABC" is of type char[4], which is implicitly converted to char* in most, but not all, contexts. (Attempting to modify a string literal has undefined behavior, but for historical reasons they're not const.) Commented Sep 6, 2014 at 20:09

2 Answers 2

3
char *a = "ABC"; 

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

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

5 Comments

Are you sure it is true in C99 and in C11 ?
@BasileStarynkevitch yes
@BasileStarynkevitch: That's the only kind of constant literal which is not const-modified...
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.
@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.
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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.