Reputation: 2949
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
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
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
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
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