有没有办法在C中循环使用不同类型元素的结构?

dri*_*ker 20 c struct loops

我的结构是这样的

typedef struct {
  type1 thing;
  type2 thing2;
  ...
  typeN thingN;
} my_struct 
Run Code Online (Sandbox Code Playgroud)

如何在循环中枚举struct childrens,例如while,或for?

phi*_*ant 42

我不确定你想要实现什么,但是你可以使用X-Macros并让预处理器在结构的所有字段上进行迭代:

//--- first describe the structure, the fields, their types and how to print them
#define X_FIELDS \
    X(int, field1, "%d") \
    X(int, field2, "%d") \
    X(char, field3, "%c") \
    X(char *, field4, "%s")

//--- define the structure, the X macro will be expanded once per field
typedef struct {
#define X(type, name, format) type name;
    X_FIELDS
#undef X
} mystruct;

void iterate(mystruct *aStruct)
{
//--- "iterate" over all the fields of the structure
#define X(type, name, format) \
         printf("mystruct.%s is "format"\n", #name, aStruct->name);
X_FIELDS
#undef X
}

//--- demonstrate
int main(int ac, char**av)
{
    mystruct a = { 0, 1, 'a', "hello"};
    iterate(&a);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这将打印:

mystruct.field1 is 0
mystruct.field2 is 1
mystruct.field3 is a
mystruct.field4 is hello
Run Code Online (Sandbox Code Playgroud)

您还可以在X_FIELDS中添加要调用的函数的名称...

  • 谢谢你向我介绍X-Macro,很棒的答案! (3认同)
  • X-Macro对我来说是一个启示.感觉有点脏,但有点正确.谢谢! (3认同)