Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we initialize members inside a structure?

Why can't we initialize members inside a structure ?

example:

struct s {    int i = 10; }; 
like image 745
Santhosh Avatar asked Oct 22 '08 10:10

Santhosh


People also ask

Can we initialize member in structure?

Structure members cannot be initialized with declaration.

Can we initialize variable in structure in C++?

// In C++ We can Initialize the Variables with Declaration in Structure. Structure members can be initialized using curly braces '{}'.

Can structure elements be initialized at the time of declaration?

A) Structure elements can be initialized at the time of declaration. Explanation: struct book { int SNO=10; //not allowed };


1 Answers

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, }; 
like image 133
Alex B Avatar answered Oct 11 '22 09:10

Alex B