String concatenation using preprocessor

前端 未结 4 1825
南方客
南方客 2020-12-11 00:33

is it possible to concatenate strings during preprocessing?

I found this example

#define H \"Hello \"
#define W \"World!\"
#define HW H W

printf(HW)         


        
4条回答
  •  粉色の甜心
    2020-12-11 01:00

    I just thought I would add an answer that cites the source as to why this works.

    The C99 standard §5.1.1.2 defines translation phases for C code. Subsection 6 states:

    1. Adjacent string literal tokens are concatenated.

    Similarly, in the C++ standards (ISO 14882) §2.1 defines the Phases of translation. Here Subsection 6 states:

    6 Adjacent ordinary string literal tokens are concatenated. Adjacent wide string literal tokens are concatenated.

    This is why you can concatenate strings simply by placing them adjacent to one another:

    printf("string"" one\n");
    
    >> ./a.out
    >> string one
    

    The preprocessing part of the question is simply the usage of the #define preprocessing directive which does the substitution from identifier (H) to string ("Hello ").

提交回复
热议问题