Home > Net >  (Why not) initialize struct val at definition
(Why not) initialize struct val at definition

Time:10-17

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

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • c c
  • Related