Do I need to use a for loop with a string macro?

I have the following definitions:

#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 the STRING_OBJECT number only with STRING_OBJECT_ + "(number string)" , so basically do not directly enter STRING_OBJECT_1 .

Is it possible to use for a loop with a string macro in C ++?

+5
source share
2 answers

Is it possible to use for a loop with a string macro in C ++?

No no.

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

The values ​​of the variables in the for loop are set at runtime. Therefore, they cannot use macros.

It is best to increment the code using an array variable and use the array variable in a 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]); } 
+5
source

No. You cannot do this. macros are not part of the C / C ++ language .

Macros are replaced by the preprocessor based on the compilation time value. Unable to change macro at runtime .

+2
source

All Articles