简体   繁体   中英

Regarding struct initialization in c++

I have Struct like these

 typedef struct sample
 {
       double x,
       double y,
       double z
 }s1;
 s1 s;

will the content in s variable initialized or not?

What will be the values of x,y,z?

thanks

x , y and z won't be initialized if s is defined in a function scope. They would be containing some unspecified values. At file scope the data members would be initialized to their default values.

In C++ however you can have a constructor initializer list to initialize the data members

For example

struct ABC
{
   int x;
   int y;

   ABC(): x(1),y(2){}
};

ABC s; // x and y initialized to 1 and 2 respectively

In C++ you also have default initialization and value initialization to initialize data members.

In the code you presented, the fields will be uninitialized. You can add a constructor (if you need/can), or in case you need the POD-ness (some part of your code depends on some of those properties) and you cannot add a constructor, you can still value-initialize the struct (ie set each member to 0) at the place of use:

struct sample        // typedef not required
{
   double x,
   double y,
   double z
};
sample s = sample(); // will set all members to 0.0

Now, if you want to initialize different members with some particular values, because it is an aggregate you can use aggregate initialization:

sample s = { 1.0, 3.0 };

That will set x to 1.0 , y to 3.0 . Since there is no value for z , the compiler will set it to 0.0 . Note that this means that sample s = {}; is equivalent to sample s = sample();

If it is C++, you could make constructor.

struct s1
{
  s1( const double x = 0.0, const double y = 0.0, const double z = 0.0 )
  : x(x), y(y), z(z)
  {
  };
  double x;
  double y;
  double z;
};

s1 s;

Built-in types like double and int are initialised if the variable is static or at namespace /file scope, otherwise - for efficiency reasons - they're not initialised unless a constructor indicates that's useful.

Note: this answer addresses the "s1 s;" situation you describe. It is possible to provide an explicit initialisation when defining the variable, but that's another case.

To add a constructor so:

struct X
{
    X() : x_(0), y_(0), z_(0) { }
    double x, y, z;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM