-1

I have variables a1, a2...a32 so How do I define them using macro?

I tried

#define Name(i) a##i
for(int i=1; i<32;i++)
{
   Name(i) = 1;
}

but actually Name(i) gives me

 ai

instead of

a1 ... a32

ps:

I do know vector. But now the variable names are given, so I can't just write array[i]=1, I have to write a1=1; ...; a32=1 etc, which makes me wanna use macro.

n0p
  • 3,399
  • 2
  • 29
  • 50
Lynton
  • 257
  • 5
  • 12
  • 1
    Use `BOOST_PP_REPEAT` and `BOOST_PP_SUB`. Still, what you've shown doesn't require decreasing numbers or 32 variables. – chris Nov 25 '14 at 07:11
  • 1
    You can't do this with macros. Look at `std::vector`. **books:** http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Galik Nov 25 '14 at 07:11
  • You cannot combine macros and c code that way. For this to work you would have to write the loop using the macro language, but there's no such thing. – didierc Nov 25 '14 at 07:14
  • I can't use boost in my project. I do know vector. But now the variable names are given, so I can't just write `array[i]=1`, I have to write `a1=1; ... a32=1`...which makes me wanna use macro. – Lynton Nov 25 '14 at 07:15
  • 2
    Well, `i` is what you pass to the macro. Think about when the preprocessor runs. Hint: not at runtime. – fredoverflow Nov 25 '14 at 07:24
  • Sorry, actually it's possible to implement loops in C macros:http://stackoverflow.com/questions/319328/writing-a-while-loop-in-the-c-preprocessor – didierc Nov 25 '14 at 07:26

2 Answers2

3

You should use an array-like container (std::array or std::vector):

std::array<Type, 32> a;

and the loop trough it with:

for (auto element : a) { ... }

or use any standard algorithm.

When you have a bunch of numbered variables, that's usually a code smell for something that should be an array.

Shoe
  • 74,840
  • 36
  • 166
  • 272
  • I do know vector. But now the variable names are given, so I can't just write `array[i]=1`, I have to write `a1=1; ... a32=1`...which makes me wanna use macro. – Lynton Nov 25 '14 at 07:19
1

There is no reason in real world programming why you would be "given" variable names. But if you for reasons unknown must use those names, then put them in a union.

typedef struct
{
  int a1;
  int a2;

  ...

  int a32;
} variables;

typedef union
{
  variables var;
  int array [32];
} my_union;


my_union mu;

for(int i=0; i<32; i++)
{
  mu.array[i] = ...;
}
Lundin
  • 195,001
  • 40
  • 254
  • 396
  • Thank you, this is better. And when you are working in a complex project with hundreds of guys and many systems, you would know what I am saying. – Lynton Nov 25 '14 at 07:31
  • 2
    @Lynton No, if you are working in such a system and you get handed something with fundamentally wrong program design, you tell them that the program needs to rewritten. Or the project will rapidly code rot. – Lundin Nov 25 '14 at 07:37