Tolik Tsay
Tolik Tsay

Reputation: 11

When defining a struct full of members, are these members created for each variable of this struct type?

so there is a code:

struct ACDC
{
  double in, out, A, B, C;
};

struct VALUE
{
  struct ACDC I, V;
};

struct VALUE motor1, motor2, DC;

When I declare a few variables of this struct like motor1, motor2, DC1, DC2, I don't need to use all the members for all the variables. I only need something like:

motor1.I.A; motor1.I.B; motor1.I.C;
motor2.I.A; motor2.I.B; motor2.V.A; motor2.V.B;
DC.I.in;
DC.I.out;

So the question is, are the other members declared for the variable and take the space in the memory when I create it? If so, how to do that they're created only when first called?

Thanks

Upvotes: 0

Views: 77

Answers (2)

kfsone
kfsone

Reputation: 24249

A struct describes a memory layout. When you instantiate one it allocates memory for the whole thing and the member names are essentially mnemonics for the offsets into that allocation, which requires they be known at compile time.

If you want optional elements, you would have to use pointers or possibly some complex template shenanigans over pointers in C++.

Because you specified two very different languages (C vs C++) I can't give a specific, idiomatic example.

However, the example you gave just looks like bad/sloppy design rather than a genuine need for variable optional membership.

You might want to show the problem you are trying to solve as a new question.

Upvotes: 3

Kiloreux
Kiloreux

Reputation: 2246

The correct answer is it depends.

If you use a high-level optimization from the compiler (say -O2 for example) then unless those variable are used somewhere they are going to get canceled by the compiler. Otherwise memory will be allocated for them.

Also about individual struct members, Yes, the struct will be allocated as a whole and not by members (check padding also for better understanding).

Upvotes: 1

Related Questions