Galaxy
Galaxy

Reputation: 2481

Can a string literal be concatenated with a char*?

I know that in C adjacent string literals are concatenated. I want to know, are adjacent string literals concatenated with char*s?

The reason I'm asking this question is because I want to pass a concatenation of two strings to perror(), and one of the strings is not known in advance so I have to use a char*.

perror("error opening " "file.txt");  // string literals are concatenated

char* filename = "file.txt";  // or some other file
perror("error opening " filename);    // will this work?

Upvotes: 1

Views: 428

Answers (2)

Amadan
Amadan

Reputation: 198324

No. Adjacent string literals being concatenated is a capability of the compiler, which treats adjacent string literals as one string literal, in order to help coders write readable code (in case of a large string literal that would not fit on a line nicely).

C as a language does not have a concatenation operator, the closest you can get to it is a function (strncat, strcat. strcpy, memcpy).

Upvotes: 4

Eric Postpischil
Eric Postpischil

Reputation: 222754

No. Concatenation of string literals is performed during translation (compilation). The operation you are requesting must be done within the program when it is executing. There is no provision for doing it automatically; you must write code to allocate space for the resulting string and to perform the concatenation.

Upvotes: 5

Related Questions