What does "a ## b" mean in C?
From usbtiny / defs.h (AVR libc USB code for ATTiny controllers):
#define CAT2(a,b) CAT2EXP(a, b)
#define CAT2EXP(a,b) a ## b
#define CAT3(a,b,c) CAT3EXP(a, b, c)
#define CAT3EXP(a,b,c) a ## b ## c
What is the ## operator? I have been doing this for 30 years and I am stumped. And Google is not helping because I don't think they are indexing those characters.
source to share
A character ##
in a macro definition is a concatenation.
So,
#define concat(a,b) a ## b
would mean that
concat (pri, ntf) ("hello world\n");
post-processes in
printf("hello world\n");
The documentation is here .
The stringify operator ( #
) is similarly useful , which should not be confused with.
Test:
/* test with
* gcc -E test.c
* having removed the #include lines for easier to read output
*/
#include <stdio.h>
#include <stdlib.h>
#define concat(a,b) a ## b
int
main (int argc, char **argv)
{
concat (pri, ntf) ("Hello world\n");
exit (0);
}
And why an additional level of indirection? As Deduplicator points out in the comments to his answer below, without this it will concatenate the specified literal terms rather than macro-substituted terms. A helpful list of such errors is here .
source to share
CAT2
and CAT3
- these are the macros to be called, the other two are part of their inner workings.
#define CAT2(a,b) CAT2EXP(a, b)
#define CAT2EXP(a,b) a ## b
So what happens if you call CAT2
?
Well, replace first CAT2
, which macro expands literals:
CAT2(a_eval, b_eval)
Which is replaced by concatenating both arguments to make one token, the concatenation operator ##
.
source to share