有什么方法可以使用for循环与字符串宏

Is there anyway to use for loop with string macro?

本文关键字:循环 字符串 for 什么 方法 可以使      更新时间:2023-10-16

我有以下定义:

#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"

我想只使用STRING_OBJECT_ + "(number string)"来编号STRING_OBJECT,所以基本上不直接键入STRING_OBJECT_1

在c++中是否有使用for循环的字符串宏?

在c++中是否有使用for循环的字符串宏?

不,没有。

在编译源代码以创建目标代码之前处理宏。

for循环中变量的值是在运行时设置的。因此,它们不能使用宏。

最好的办法是在代码中增加一个数组变量,并在for循环中使用该数组变量。

#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]);
}

,你不能这么做。不属于C/c++ 语言的宏。

预处理器按编译时间替换。您无法在运行时更改宏。