Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 755
RequireKeys Avatar asked Apr 06 '26 16:04

RequireKeys


2 Answers

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));
like image 143
Eric Postpischil Avatar answered Apr 09 '26 09:04

Eric Postpischil


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));
like image 39
ryyker Avatar answered Apr 09 '26 08:04

ryyker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!