2

So say I have a 'struct' such as this:

struct Vertex
{
    float posX, posY, posZ;
}

Where I have declared 3 float (4-byte approx) values. So all-in-all this 'struct' is about 12 bytes.

But if I write it like this:

struct Vertex
{
    float pos[3];
}

Do I still get the same effect as above? 12 bytes? What is the difference?

1
  • 5
    "So all-in-all this 'struct' is about 12 bytes." Maybe. Depends on alignment and packing (though I believe that in most cases you'll be right). If you need to know ask the compiler (with sizeof). Commented Dec 16, 2012 at 17:42

2 Answers 2

2

I can think of one diffrence: if you have a pack greater then the size of your variables, compiler will pad posX, posY, posZ to make them align nicely. It matters to you at most when you're doing a binary read/write.

Usually there is a serious performance reason to use certain padding, as feeding processor with unaligned data may have grave consequences.

Sign up to request clarification or add additional context in comments.

Comments

2

In theory in the first case the compiler is allowed to add padding between the various fields, while in the second case it's not allowed (an array must be a contiguous sequence of elements).

So, in theory the first struct may take more space, in practice they will probably have the same size/memory layout.

Obviously in the first case you can access such data using the names of the three members, while in the second case you'll use the array syntax over the pos member.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.