Search code examples
cconcatenationstring-concatenationc-stringspreprocessor-directive

Concatenate strings using ## operators in C


In C we can use ## to concatenate two arguments of a parameterized macro like so:

arg1 ## arg2 which returns arg1arg2

I wrote this code hoping that it would concatenate and return me a string literal but I cannot get it to work:

#define catstr(x, y) x##y

puts("catting these strings\t" catstr(lmao, elephant));

returns the following error:

define_directives.c:31:39: error: expected ‘)’ before ‘lmaoelephant’
   31 |         puts("catting these strings\t" catstr(lmao, elephant));
      |                                       ^
      |                                       )

It seems the strings are concatenating but they need to be wrapped around quotes in order for puts to print it. But doing so, the macro no longer works. How do I get around this?


Solution

  • To use the call to puts() in this way, the macro catstr() should be constructed to do two things:

    • stringify and concatenate lmao to the string "catting these strings\t"
    • stringify and concatenate elephant to lmao.

    You can accomplish this by changing your existing macro definition from:

    #define catstr(x, y) x##y
    

    To:

    #define catstr(x, y) #x#y
    

    This essentially result in:

    "catting these strings\t"#lmao#elephant
    

    Or:

    "catting these strings   lmaoelephant"  
    

    Making it a single null terminated string, and suitable as an argument to puts():

    puts("catting these strings\t" catstr(lmao, elephant));