Home > Mobile >  Initialization of structs in C
Initialization of structs in C

Time:10-29

I stumbled upon this weird struct implementation(from a big project) and I wanted to know the difference between this one and the normal one and why is it even implemented this way :

struct Sabc{
   Sabc()
   {
       A = 0;
       B = 0.0f;
   }
   int A;
   float B;
}

Why not just :

struct Sabc{
   Sabc()
   {
      int A = 0;
      float B = 0.0f;
   }
}

Or why not even this way:

struct Sabc{
   int A = 0;
   float B = 0.0f;
}

CodePudding user response:

Declare a struct with two members, explicitly overrides the default c'tor and initializes both members 0 and 0.0f:

struct Sabc{
   Sabc()
   {
       A = 0;
       B = 0.0f;
   }
   int A;
   float B;
}

Declares a struct with no members, and explicitly override the default c'tor, within it declare two local variables, initialize with values, and on c'tor return, variables go out of scope and are deleted:

struct Sabc{
   Sabc()
   {
      int A = 0;
      float B = 0.0f;
   }
}

Declares a struct with two members, and implicitly default initialize to 0 and 0.0f, only compiles in C :

struct Sabc{
   int A = 0;
   float B = 0.0f;
}
  • Related