Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anyway to use for loop with string macro?

Tags:

c++

macros

I have the following defines:

#define STRING_OBJECT_1 "bird"
#define STRING_OBJECT_2 "dog"
#define STRING_OBJECT_3 "cat"
#define STRING_OBJECT_4 "human"
#define STRING_OBJECT_5 "cow"
#define STRING_OBJECT_6 "snake"
#define STRING_OBJECT_7 "penguin"
#define STRING_OBJECT_8 "monkey"

I want to get numbered STRING_OBJECT only using STRING_OBJECT_ + "(number string)", so basically not directly type STRING_OBJECT_1.

Is there anyway to use for loop with string macro in C++?

like image 869
JongHyeon Yeo Avatar asked Aug 12 '16 04:08

JongHyeon Yeo


2 Answers

Is there anyway to use for loop with string macro in C++?

No, there isn't.

Macros are processed before source code is compiled to create object code.

The values of variables in a for loop are set at run time. Hence, they cannot make use of macros.

Your best bet is to augment your code with an array variable and use the array variable in the for loop.

#define STRING_OBJECT_1 "bird"
...
#define STRING_OBJECT_8 "monkey"

std::string object_array[] = {STRING_OBJECT_1, ..., STRING_OBJECT_8};

for ( int i = 0; ... )
{
   do_something(object_array[i]);
}
like image 157
R Sahu Avatar answered Sep 30 '22 15:09

R Sahu


No, You can't do this. macros not part of the C/C++ language.

Macros are replaced by the preprocessor by their value compiles time. There is no way you had be able to change the macro at runtime.

like image 41
msc Avatar answered Sep 30 '22 14:09

msc