Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating a struct in C++

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++?

like image 791
Eyal D Avatar asked Feb 12 '23 08:02

Eyal D


2 Answers

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 };
like image 81
Dai Avatar answered Feb 19 '23 21:02

Dai


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
}
like image 30
Trevor Hickey Avatar answered Feb 19 '23 19:02

Trevor Hickey