Eyal D
Eyal D

Reputation: 181

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

Upvotes: 4

Views: 124

Answers (4)

Jarod42
Jarod42

Reputation: 217663

You may use the C-way as it is a pod:

memset(&str_instance, '\0', sizeof(str));

Upvotes: 0

Trevor Hickey
Trevor Hickey

Reputation: 37874

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
}

Upvotes: 1

Dai
Dai

Reputation: 155330

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

Upvotes: 7

Codor
Codor

Reputation: 17605

If the struct members are enabled and disabled by defines, then there is no other possiblity than to use the same defines for access to values of the struct. However, a struct might not be the best choice if flexibility is needed.

Upvotes: 0

Related Questions