Skip to content

Instantly share code, notes, and snippets.

@simonhf
Created August 12, 2014 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonhf/12c04ce78586d1cc7284 to your computer and use it in GitHub Desktop.
Save simonhf/12c04ce78586d1cc7284 to your computer and use it in GitHub Desktop.
How to use macros to name unique variables?
#include <stdio.h>
#define TOKENPASTE2(x, y) x ## y
#define TOKENPASTE(x, y) TOKENPASTE2(x, y)
#define FOO TOKENPASTE(var_, __LINE__)
#define BAR __LINE__
void
main(void)
{
int FOO = BAR; printf("hello world! %d %d\n", FOO, var_11);
int FOO = BAR; printf("hello world! %d %d\n", FOO, var_12);
int FOO = BAR; printf("hello world! %d %d\n", FOO, var_13);
}
// $ ( gcc -E main.c | egrep hello ); gcc -o main main.c && ./main
// int var_11 = 11; printf("hello world! %d %d\n", var_11, var_11);
// int var_12 = 12; printf("hello world! %d %d\n", var_12, var_12);
// int var_13 = 13; printf("hello world! %d %d\n", var_13, var_13);
// hello world! 11 11
// hello world! 12 12
// hello world! 13 13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment