3

I'm trying to use macro for c code. However, I stuck in using token concatenation

I have below variables.

A, aA, bA, cA ...

And, all of these variables used for same function (situation is a bit complicate, so just passing variable is not enough).

If I have only

aA, bA, cA

Then, I can do using the below macro.

#define CALL_FUNCTION(GROUP) \
     FUNCTION(GROUP##A);

However, because of

A

I can't use the mentioned macro anymore. I tried,

#define CALL_FUNCTION(GROUP) \
     FUNCTION(GROUP##A);

FUNCTION(NULL);    
FUNCTION(a);
FUNCTION(b);
FUNCTION(c);

But actually, NULL is not empty string, it didn't work.

FUNCTION("");    

Also didn't work.

There are alternative way like,

#define CALL_FUNCTION(GROUP) \
    if(GROUP == NULL)\
        FUNCTION(A);\
    else\
        FUNCTION(GROUP##A);

However, in this case, I need to write few lines more. In my case, it cause much more codes.

I googled a lot, but I couldn't solution. Is there anyone who knows how to token paste with empty string?

Thanks

user2268721
  • 175
  • 1
  • 13

2 Answers2

3

Pass an empty argument and it will effectively concatenate nothing with A, producing just A:

#define CALL_FUNCTION(GROUP) \
     FUNCTION(GROUP##A);

CALL_FUNCTION() // expands to FUNCTION(A);
CALL_FUNCTION(a) // expands to FUNCTION(aA);

You can see this work live.

The thing to note is that when you call CALL_FUNCTION(), you do not pass zero arguments, as you do with functions. Instead, you pass a single argument - empty. Similarly, MACRO(,) calls MACRO with two empty arguments. It just so happens that the concatenation behaviour with empty is what you want.

chris
  • 60,560
  • 13
  • 143
  • 205
1

You just need a second macro that takes no parameters:

#define CALL_FUNCTION() \
     FUNCTION(A);

#define CALL_FUNCTION(GROUP) \
     FUNCTION(GROUP##A);

Example:

#include <stdio.h>

#define FUNCTION(x)           printf( # x "\n" )
#define CALL_FUNCTION()       FUNCTION(A)
#define CALL_FUNCTION(GROUP)  FUNCTION(GROUP##A)

int main(void) {
    CALL_FUNCTION();
    CALL_FUNCTION(a);
    CALL_FUNCTION(b);
    CALL_FUNCTION(c);
    return 0;
}

Output:

A
aA
bA
cA
paddy
  • 60,864
  • 6
  • 61
  • 103
  • Your example gives me a [warning](http://coliru.stacked-crooked.com/a/35e09df47fec9fbd) about the macro being redefined. It just so happens by luck that the redefinition handles both empty arguments and non-empty ones. – chris Feb 02 '16 at 06:23