Having a structure like this in C++11:
struct von
{
std::string Name;
unsigned int ID;
std::vector<std::string> Checks;
};
Should it be initialized like this:
von v = {"",0,{}};
Or like this:
von v = {};
Both ways seem to work, but the compiler warns about -Wmissing-field-initializers
on the latter example.
Edit:
Here are my compiler options:
g++ main.cpp -ansi -Wall -Wextra -Weffc++ -std=c++0x
I'm using g++ (Debian 4.6.2-12) 4.6.2
Generally, the initialization of the structure variable is done after the structure declaration. Just after structure declaration put the braces (i.e. {}) and inside it an equal sign (=) followed by the values must be in the order of members specified also each value must be separated by commas.
myStruct = (MyStruct*)calloc(1, sizeof(MyStruct)); should initialize all the values to zero, as does: myStruct = new MyStruct(); However, when the struct is initialized in the second way, Valgrind later complains "conditional jump or move depends on uninitialised value(s)" when those variables are used.
When initializing a struct, the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99), and all subsequent initializers without designators (since C99)initialize the struct members declared after the one initialized by the previous expression.
Initializing structure members struct car { char name[100]; float price; }; //car1 name as "xyz" //price as 987432.50 struct car car1 ={"xyz", 987432.50};
This doesn't require initializer_list at all and work perfectly fine with C++03. Edit: (Ok, for the initialization of the vector you need C++11) In a struct or array initialization, all not explicitly given values are zero-initialized, so if that's what you want = {}; will work just fine.
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