In C we can use ## to concatenate two arguments of a parameterized macro like so:
arg1##arg2which returnsarg1arg2
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?
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));
To use the call to puts() in this way, the macro catstr() should be constructed to do two things:
lmao to the string "catting these strings\t"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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With