且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否有通过在C diferent类型的元素一个struct任何方式循环?

更新时间:2021-08-18 05:07:36

我不知道你想达到什么,但你可以使用 X-宏 并有preprocessor做迭代通过结构的所有字段:

I'm not sure what you want to achieve, but you can use X-Macros and have the preprocessor doing the iteration over all the fields of a structure:

//--- 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;
}

这会打印:

mystruct.field1 is 0
mystruct.field2 is 1
mystruct.field3 is a
mystruct.field4 is hello

您也可以添加函数的名称在X_FIELDS调用...

You can also add the name of the function to be invoked in the X_FIELDS...