carloabelli
carloabelli

Reputation: 4349

Use Parameter Name of #define in another #define

Is there a way to use the name of a #define parameter as another #define parameter? For example:

#define TEST 1

#define FOO(X) foo_##X

#define BAR(X) FOO(##X)

BAR(TEST)

Where it results in:

foo_TEST

Not:

foo_1

This doesn't work as it gives:

pasting "(" and "TEST" does not give a valid preprocessing token

Upvotes: 0

Views: 1163

Answers (2)

jweyrich
jweyrich

Reputation: 32261

There are only 2 ways to avoid evaluation of a macro argument. Use the # (stringize) processing operator or the ## (token pasting) operator on it.

Try the following:

#include <stdio.h>

#define TEST 1

#define FOO(X) foo ## X
#define BAR(X) FOO(_ ## X) // Prevent the evaluation of X with ##

void foo_1()
{
    printf("%s\n", __FUNCTION__);
}

void foo_TEST()
{
    printf("%s\n", __FUNCTION__);
}

int main()
{
    BAR(TEST)();
    return 0;
}

Upvotes: 1

Zelldon
Zelldon

Reputation: 5516

Remove the double '#' in the BAR marco.

See the working example: http://ideone.com/hEhkKn

#include <stdio.h>

#define FOO(X) foo_##X

#define BAR(X) FOO(X)


int main(void) {

    int BAR(hello);
    return 0;
}

Regarding to your updated question:

If you want to use a defined name like 'TEST', so change your code to #define TEST TEST

#include <stdio.h>

#define TEST TEST    
#define FOO(X) foo_##X    
#define BAR(X) FOO(X)

int BAR(TEST) (int v) {
    return v;
}

int main(void) {
    return foo_TEST(0);
}

Upvotes: 2

Related Questions