Is sizeof() recursive?

The answer should be simple, but I wanted to make sure.

Is sizeof() recursive? For instance,

struct foo
{
   DWORD a;
   DWORD b;
};

struct bar
{
   DWORD c;
   foo d;
};

would a sizeof(bar) include the size of foo, returning a full 12 bytes (assuming DWORD is 4 bytes)?

Upvotes: 3

Views: 922

Answers (3)

Tony Delroy
Tony Delroy

Reputation: 106236

Yes... sizeof gives a total of all the members directly included in the type, including struct/class data members, non-virtual base classes, some implementation-defined links/counters tracking virtual bases, virtual dispatch table pointers, padding that helps align data members for CPU-safe or -efficient access, and theoretically anything else the implementation may feel like putting in there! (for example, something for run-time debugging / error detection, non-Standard support of garbage collection...)

Of course, it doesn't include the size of pointed-to or referenced objects, but does include the size of those pointers and references.

Upvotes: 6

Hristo Iliev
Hristo Iliev

Reputation: 74475

Yes, it is. Excerpt from ISO/IEC 9899:TC3:

When applied to an operand that has structure or union type, the result is the total number of bytes in such an object, including internal and trailing padding.

(emphasis mine)

Upvotes: 3

Alok Save
Alok Save

Reputation: 206606

Yes, the sizeof operator gives you size of the structure including all its members.

But note that an compiler may add its own padding, so actual size may/may not be equal to sum of sizes of structure members.

Upvotes: 6

Related Questions