String concatenation behavior in C

Asked

Viewed 58 times

4

Why the following C code works?

char *str = "A""B"; /* str = "AB" */


However I noticed that it is only in string statements, for example the following would not work:

char *a = "A";
char *ab = a "B"; /* Funcionaria se a fosse uma macro */


I suspect it works because the compiler considers "A""B" as a single memory block and make the "concatenation" automatically.

In short I would like to know if my assumption is right or is for another reason.

1 answer

4


Because the C compiler glues/concatenates literals of consecutive strings.

For example:

#include<stdio.h>
int main() {
    const char *hw = ""
        "Hello"
        " "
        "World" "!" "!" "!";

    printf("%s", hw);
}

Produces as output:

Hello World!!!

See here working on ideone.

However, this only applies to literal strings. It doesn’t work with variables or other things.

  • so somehow my guess was right?

  • @Jonathagabriel Yes. The compiler makes a VIP treatment for string literals by considering them as a single string.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.