tags:

views:

879

answers:

5

Why can't we initialize members inside the structure ?

example:

struct s {
   int i=10;
};

Thanks in advance

+8  A: 

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,
};
Alex B
+2  A: 

Edit: The question was originally tagged c++ but the poster said it's regarding c so I re-tagged the question, I'm leaving the answer though...

In C++ a struct is just a class which defaults for public rather than private for members and inheritance.

C++ only allows static const integral members to be initialized inline, other members must be initialized in the constructor, or if the struct is a POD in an initialization list (when declaring the variable).

struct bad {
    static int answer = 42; // Error! not const
    const char* question = "what is life?"; // Error! not const or integral
};

struct good {
    static const int answer = 42; // OK
    const char* question;
    good() 
        : question("what is life?") // initialization list
        { }
};

struct pod { // plain old data
    int answer;
    const char* question;
};
pod p = { 42, "what is life?" };
Motti
A: 

Thanks for the comments, i am asking with respect C Language.

Santhosh
+5  A: 

The direct answer is because the structure definition declares a type and not a variable that can be initialized. Your example is:

struct s { int i=10; };

This does not declare any variable - it defines a type. To declare a variable, you would add a name between the } and the ;, and then you would initialize it afterwards:

struct s { int i; } t = { 10 };

As Checkers noted, in C99, you can also use designated initializers (which is a wonderful improvement -- one day, C will catch up with the other features that Fortran 66 had for data initialization, primarily repeating initializers a specifiable number of times). With this simple structure, there is no benefit. If you have a structure with, say, 20 members and only needed to initialize one of them (say because you have a flag that indicates that the rest of the structure is, or is not, initialized), it is more useful:

struct s { int i; } t = { .i = 10 };

This notation can also be used to initialize unions, to choose which element of the union is initialized.

Jonathan Leffler
A: 

Why? Because the standard doesn't allow it.

Is it inconvenient? Yes.

MSN

MSN