Home >Backend Development >C++ >How Can I Directly Concatenate String Literals in C/C Macros?

How Can I Directly Concatenate String Literals in C/C Macros?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-20 14:50:16913browse

How Can I Directly Concatenate String Literals in C/C   Macros?

String Concatenation in C/C Macros

When defining macros with string literals, it's often necessary to concatenate them to form a new string. Let's consider an example:

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

The question arises: is it possible to directly concatenate STR1 and STR2 to obtain "s1" using a single macro definition?

Standard String Concatenation

Traditionally, string concatenation in macros is achieved by utilizing the stringification operator (#). However, this approach entails passing arguments to an intermediate macro function.

#define CONCAT(x, y) x ## y
#define STR3 CONCAT(STR1, STR2)

Simplified Concatenation for Strings

For the specific case of concatenating string literals, a simplified approach exists. By omitting the stringification operator, we can directly concatenate the strings:

#define STR3 STR1 STR2

This expands to:

#define STR3 "s" "1"

In the C language, juxtaposing strings with spaces (as in "s" "1") is equivalent to having a single string "s1". Therefore, this simplified method provides a direct way to concatenate string literals in C/C macros.

The above is the detailed content of How Can I Directly Concatenate String Literals in C/C Macros?. 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