Home >Backend Development >C++ >How Can I Concatenate Macro-Defined Strings in C/C Without the Operator?

How Can I Concatenate Macro-Defined Strings in C/C Without the Operator?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-07 06:32:18640browse

How Can I Concatenate Macro-Defined Strings in C/C   Without the  Operator?

Macro-Based String Concatenation in C/C

Directly concatenating macro-defined strings in C/C is not possible using the ## preprocessor operator, which is primarily intended for token concatenation. However, a workaround exists to achieve this.

Consider the following example:

#define STR1      "s"
#define STR2      "1"
#define STR3      STR1 STR2

This code defines three macros: STR1 with the string literal "s", STR2 with "1", and STR3 as the concatenation of STR1 and STR2. The expansion of STR3 results in:

#define STR3 "s" "1"

However, in the C language, the juxtaposition of two strings separated by whitespace (as in "s" "1") is equivalent to a single string "s1".

Therefore, the following code directly concatenates STR1 and STR2 without the need for the ## operator:

#define STR3 STR1 STR2

This expands to:

#define STR3 "s1"

The above is the detailed content of How Can I Concatenate Macro-Defined Strings in C/C Without the Operator?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn