RequireKeys
RequireKeys

Reputation: 538

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?

Upvotes: 3

Views: 1033

Answers (2)

ryyker
ryyker

Reputation: 23218

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));

Upvotes: 1

Eric Postpischil
Eric Postpischil

Reputation: 222486

You do not need to use ## to concatenate strings. C already concatenates adjacent strings: "abc" "def" will become "abcdef".

If you want lmao and elephant to become strings (without putting them in quotes yourself for some reason), you need to use the stringize operator, #:

#define string(x) #x

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

Upvotes: 5

Related Questions