I'm having some trouble iterating over a struct.
The struct can be defined differently, depending on the compiler flags. I want to set all the struct members to 0. I don't know how many members there are, but they are all guaranteed to be numbers (int, long...)
See the example below:
#ifdef FLAG1
    struct str{
        int i1;
        long l1;
        doulbe d1;
    };
#elsif defined (OPTION2)
    struct str{
        double d1
        long l1;
    };
#else
    struct str{
        int i1;
    };
#endif
I guess a good pseudo-code for what I want to do is:
void f (str * toZero)
{
    foreach member m in toZero
        m=0
}
Is there a way to easily do that in c++?
To initialise any PODO's data to zero in C++ use = { 0 }. You don't need to iterate over every member.
StructFoo* instance = ...
*instance = { 0 };
                        For simplicity, You may want to consider using a single macro in the following way:
#define NUMBER_OF_MEMBERS 3
struct Str{
#if NUMBER_OF_MEMBERS > 0
    int i1;
#endif
#if NUMBER_OF_MEMBERS > 1
    double d1;
#endif
#if NUMBER_OF_MEMBERS > 2
    long l1;
#endif
};
void f (Str & str){
    #if NUMBER_OF_MEMBERS > 0
        str.i1 = 0;
    #endif
    #if NUMBER_OF_MEMBERS > 1
        str.d1 = 0;
    #endif
    #if NUMBER_OF_MEMBERS > 2
        str.l1 = 0;
    #endif
    return;
}
int main() {
    Str str;
    f(str);
}
Secondly, are you only calling the f function after you create the class to start the values at zero?  If so, this is better suited for the struct's constructor method.  In C++11, it could be written as cleanly as this:
#define NUMBER_OF_MEMBERS 3
struct Str{
#if NUMBER_OF_MEMBERS > 0
    int i1 = {0};
#endif
#if NUMBER_OF_MEMBERS > 1
    double d1 = {0};
#endif
#if NUMBER_OF_MEMBERS > 2
    long l1 = {0};
#endif
};
int main() {
    Str str;
    //no need to call function after construction
}
                        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