l_-A-_l
l_-A-_l

Reputation: 142

(Why not) initialize struct val at definition

I know this kind of initialisation is discouraged but I can't remember why, while it's working, so does anyone knows why this should be avoided :

typedef struct struct_test {
    int a = 1;
    int b = 2;
    int c = 3;
} t_test;

thanks

Upvotes: 0

Views: 86

Answers (2)

l_-A-_l
l_-A-_l

Reputation: 142

While initializing a struct val at definition is not allowed in C It's perfectly correct in C++

the confusion can arise when compiling a .cpp with gcc that allow this syntax in this case.

Upvotes: 2

HolyBlackCat
HolyBlackCat

Reputation: 96326

It's illegal in C.

In C++ it's not discouraged. Unlike initializing in the constructor, it doesn't require you to list all fields the second time (see DRY), making it harder to forget to initialize fields.

Upvotes: 2

Related Questions