Home > Enterprise >  Itering and compare struct element with different size
Itering and compare struct element with different size

Time:05-03

I've a tricky question and I don't know if there is any solution.

Basically I've populated a struct using x-macros, for example with the following macro:

#define X_MACRO_TABLE(_) \
_(var_1 , type1)\
_(var_2, type2)\
_(...., ....)\
_(var_n, type_n)\

I can have an output like that:

    typedef struct __attribute__((packed, aligned(1)))
    {
        union {
            struct __attribute__((packed, aligned(1))) data{
                type_1 var_1;
                type_2 var_2;
                ....
                type_n var_n;
            }data_s;
            uint8 DataArray[sizeof(struct data)];
        };
    }data_t;

It is something I often do and it's works fine.

Now let's say I need to define two struct:

static data_t   DataVar;
static data_t   DataVar_max;

There is any way using a loop or something to compare each element of the struct with its maximum?

DataVar.var_1 > DataVar_max.var_1 ??
DataVar.var_2 > DataVar_max.var_2 ??

Or passing through the array, due to the fact I know the types dimension, for example in case var_1 is equal to uint16_t do something like:

(DataVar.DataArray[0] DataVar.DataArray[1]<<8) > (DataVar_max.DataArray[0] DataVar_max.DataArray[1]<<8) ??

CodePudding user response:

Assuming the types can be compared with the > operator and both structs are initialized, you can simply do:

#define COMP_MEMBERS(name, type) if (DataVar.name > DataVar_max.name) { do_something(); }
...
X_MACRO_TABLE(COMP_MEMBERS)

This will expand to an if statement per member.

  • Related