Why can't we initialize members inside a structure?

Santhosh picture Santhosh · Oct 22, 2008 · Viewed 69.7k times · Source

Why can't we initialize members inside a structure ?

example:

struct s {
   int i = 10;
};

Answer

Alex B picture Alex B · Oct 22, 2008

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