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++?
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]);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With