Łukasz Przeniosło
Łukasz Przeniosło

Reputation: 2949

variable name as macro argument

I am trying to create a macro in c, that will take a variable name, and declare it. I could call it like this:

MY_MACRO(test);

Would produce:

int test;

In order to achieve this I went this way:

#define MY_MACRO(var)   /
    int ##var;          /

But the compiler doesn't understand this. Does such syntax exist in C11?

Upvotes: 1

Views: 1506

Answers (4)

0___________
0___________

Reputation: 67476

## is not applicable here as it concatenates the token with something else

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#define MY_MACRO(var) int var   

or

#define MY_MACRO(var) \
int var          \

void foo(void)
{
    MY_MACRO(a);

    a = rand();

    printf("%d\n",a);
}

Upvotes: 2

Blaze
Blaze

Reputation: 16876

I wouldn't recommend doing such a thing. Anyway, there are two problems. First of all, to skip a newline, you need \, not /.

Second, the ## is wrong. What it does is concatenating the var to the int. So with MY_MACRO(foo) you would get intfoo;, but you want int foo;

The macro needs to be like this:

#define MY_MACRO(var)   \
int var 

Upvotes: 4

Gamification
Gamification

Reputation: 827

The correct syntax would be something along the lines of this:

#define MY_MACRO(ident) \
    int ident

int main() {
    MY_MACRO(test);
    test =42;
    return test;
}

However, have you been looking into typedefs? Unlike typedefs, macros are considered bad practice.

Upvotes: 0

molbdnilo
molbdnilo

Reputation: 66371

## pastes two tokens together into one token.

#define poem(var)\
    int jack##var;

// Produces 'int jacksprat;'
poem(sprat)

In your case you don't need to do anything special at all, you can just use the argument directly:

#define MY_MACRO(var)\
    int var;

Upvotes: 1

Related Questions