Why can't we initialize members inside a structure ?
example:
struct s { int i = 10; };
Structure members cannot be initialized with declaration.
// In C++ We can Initialize the Variables with Declaration in Structure. Structure members can be initialized using curly braces '{}'.
A) Structure elements can be initialized at the time of declaration. Explanation: struct book { int SNO=10; //not allowed };
If you want to initialize non-static members in struct
declaration:
In C++ (not C), structs
are almost synonymous to classes and can have members initialized in the constructor.
struct s { int i; s(): i(10) { } };
If you want to initialize an instance:
In C or C++:
struct s { int i; }; ... struct s s_instance = { 10 };
C99 also has a feature called designated initializers:
struct s { int i; }; ... struct s s_instance = { .i = 10, };
There is also a GNU C extension which is very similar to C99 designated initializers, but it's better to use something more portable:
struct s s_instance = { i: 10, };
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