litro
litro

Reputation: 529

behaviour of tiny c++ structs

If I define a struct like:

struct tiny
{
    long t;
};

will it be handled like a long in terms of function arguments and alike, in example would the parameter of:

void myfunc(tiny x)
{ ... }

be handled like a long parameter by actually being pushed on the stack?

So essentially, is the tiny struct only as large as a its sole member?

Thanks

Upvotes: 6

Views: 196

Answers (3)

Luther
Luther

Reputation: 1848

If you start adding virtual functions, it will increase by 4 bytes on most systems/compilers (and an extra 4 bytes for every interface you include). Generally speaking, the struct should be the same size as the contents unless the compiler has added extra padding as Aviv said.

Have a look at #pragma pack(n)for packing issues, at least in Visual Studio (Microsoft page on pragma pack)

Upvotes: -1

Aviv A.
Aviv A.

Reputation: 697

The memory consumption of a structure is at least the sum of the memory sizes of constituent variables.

However, the compiler may add padding between the variables or at the end of the structure to ensure proper data alignment for a given computer architecture

Upvotes: 7

Jerry Coffin
Jerry Coffin

Reputation: 490728

There's no guarantee of it, but at least with the compilers I've looked it it normally will be, yes.

Upvotes: 7

Related Questions