9

Possible Duplicate:
C preprocessor and concatenation

Is it possible to concatenate a C preprocessor with a variable name?

#define  WIDTH 32

int dataWIDTH;


// dataWIDTH should be interpreted as 'data32'

printf("%d",dataWIDTH);
Community
  • 1
  • 1
Jean
  • 21,665
  • 24
  • 69
  • 119

2 Answers2

17

Your use case requires a double-unescaping; using the token pasting (##) operator by itself will just append the name of the preprocessor directive.

#define WIDTH 32

#define _MAKEDATA(n) data##n
#define MAKEDATA(n) _MAKEDATA(n)

int MAKEDATA(WIDTH) = 7;
int _MAKEDATA(WIDTH) = 8;

int main(int argc, char *argv[]) {
    printf("%d\n", data32);
    return 0;
}

yields

$ gcc -E foo.c 
int data32 = 7;
int dataWIDTH = 8;

int main(int argc, char *argv[]) {
    printf("%d\n", data32);
    return 0;
}
user295691
  • 7,108
  • 1
  • 26
  • 35
  • 2
    Also, see http://stackoverflow.com/questions/1489932/c-preprocessor-and-concatenation for an excellent discussion of the double-pasting "trick" – user295691 Dec 17 '12 at 22:50
1

There's a token pasting operator called ##, read about it for example here:

http://msdn.microsoft.com/en-us/library/09dwwt6y(v=vs.80).aspx

Per Ersson
  • 771
  • 2
  • 6
  • 10
  • 1
    The preprocessor expands this to `printf("%d", data##32)`, which yields a compiler error. My understanding is that token pasting only works inside of macros. – user295691 Dec 17 '12 at 23:05
  • That example was added by another user, the provided link shows how to use token-pasting from within a macro. – Per Ersson Dec 18 '12 at 09:48