String concatenation using preprocessor

前端 未结 4 1822
南方客
南方客 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 00:58

    You can indeed concatenate tokens in the preprocessor, but be careful because it's tricky. The key is the ## operator. If you were to throw this at the top of your code:

    #define myexample(x,y,z) int example_##x##_##y##_##z## = x##y##z 
    

    then basically, what this does, is that during preprocessing, it will take any call to that macro, such as the following:

    myexample(1,2,3);
    

    and it will literally turn into

    int example_1_2_3 = 123;
    

    This allows you a ton of flexibility while coding if you use it correctly, but it doesn't exactly apply how you are trying to use it. With a little massaging, you could get it to work though.

    One possible solution for your example might be:

    #define H "Hello "
    #define W "World!"
    #define concat_and_print(a, b) cout << a << b << endl
    

    and then do something like

    concat_and_print(H,W);
    

提交回复
热议问题