Search code examples
c++struct

How to initialize a struct with enum member?


I have a struct with many members and with different types (it's like 20 members):

enum TheEnum
{
    FIRST = 0,
    SECOND,
    ...
}

struct TheStruct
{
    TheEnum z; // <--- the point !!! note that this is the first member (edited)
    int a;
    int b;
    char c[32];
    ...
}

Due to there is an enum type member, I cant just declare like:

TheStruct Object = {0};

It will give compile error, but this initialization is the best way in my opinion.

The other ways that I can think of is:
1. ZeroMemory it, but I dont like this one.
2. Write a constructor, but this needs a lot of work.
3. Just don't initialize it.

So, is there any way to solve the enum problem? Should I pick a way in these 3?
Thanks!

EDIT: My big mistake, the error only occurs when TheEnum presents as the first member.
Compiled using vs2008 and as C++ code.
The error is C2440. http://msdn.microsoft.com/en-us/library/sy5tsf8z%28v=VS.80%29.aspx


Solution

  • [edit] as the question changed

    If you initialize a struct, you have to provide the correct types in your initializer. In your case, the correct initialization would look like this:

    TheStruct Object = {FIRST};
    

    Your initialization list initializes the given number of struct members with what you have written and the rest of the struct with '0'. Since your first member is an enum, you have to initialize that enum in this case.

    [/edit]

    there is nothing necessary. if you're compiling in C and not C++ just don't forget to write enum and struct and everything should work...

    enum TheEnum
    {
        FIRST = 0,
        SECOND,
        ...
    }
    
    struct TheStruct
    {
        int a;
        int b;
        char c[32];
        ...
        enum TheEnum z; // <--- the point !!!
    }
    
    struct TheStruct Object = {0};