Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing the value of a variable to macro in C

I'm trying to pass the value of a variable to a macro in C, but I don't know if this is possible. Example:

#include <stdio.h>

#define CONCVAR(_n) x ## _n

int main () {
   int x0, x1, x2, x3, x4, x5, x6, x7, x8, x9;
   int i;

   for (i = 0; i <= 9; i++) CONCVAR(i) = i*5;

   return 0;
}

Here, I'm trying to use a macro to assign a value to all x_ variables, using ## tokens. I know I can easily achieve this with arrays, but this is for learning purposes only.

CONCVAR(i) is substituted to xi, not x1 (if i == 1). I know how defines and macro work, it's all about substitution, but I want to know if it is possible to pass the value of i instead the letter i to a macro.

like image 660
Fábio Perez Avatar asked Feb 16 '11 15:02

Fábio Perez


2 Answers

Substituting the value of i into the macro is impossible, since macro substitutions happen before your code is compiled. If you're using GCC, you can see the pre-processor output by adding the '-E' command line argument (Note however, that you'll see all the #include's inserted in your code.)

C is a static language and you can not decide symbol names at runtime. However, what you're trying to achieve is possible if you use an array and refer to elements using subscripts. As a rule of thumb, if you have many variables like x0, x1, etc, you should probably be using a container like an array.

like image 148
yan Avatar answered Sep 19 '22 15:09

yan


No, because the value of i only exists at run-time. Macro expansion happens at compile-time.

like image 30
Oliver Charlesworth Avatar answered Sep 20 '22 15:09

Oliver Charlesworth