Search code examples
cconstantsstring-literalscompound-literals

Difference between string literal and const char[], or char[]


Let's say I have this C code

f((char []){ "hello" });
f((const char []){ "hello" });
f("hello");

In all three cases, hello is copied into the function. a pointer to the first character of the char array is initialized as the function parameter.

I know that in C, the string literal corresponds to char [] while in C++ the string literal corresponds to const char [], but will it create the same code as with char [] or const char []?

In a C program, could you exchange all occurences of "string" with (char []){ "string" } and get the same result on the assembly level?


Solution

  • I can not say what code will be generated but according to the C Standard (6.5.2.5 Compound literals)

    7 String literals, and compound literals with const-qualified types, need not designate distinct objects.

    And there is an example

    13 EXAMPLE 6 Like string literals, const-qualified compound literals can be placed into read-only memory and can even be shared. For example,

    (const char []){"abc"} == "abc"
    

    might yield 1 if the literals’ storage is shared.

    As you correctly mentioned string literals in C have types of non constant character arrays. However they may not be modified. On the other hand a compound literal without the qualifier const can be modified. This can influence on the generated assembly code. Or if to use the qualifier const with a compound literal then the resulted type differs from the type of the corresponding string literal. So again this can influence on the generated assembly code.

    Another difference is that string literals in any case have the static storage duration but a compound literal can have the automatic storage duration. And this also can influence the generated assembly code.