|
-
December 3rd, 2010, 02:42 AM
#14
Re: struct size
 Originally Posted by ninja9578
Te reason it does that is because most computers perform much better if your memory is WORD aligned. Usually a WORD is 4 bytes, so your compiler will expand and ever rearrange your struct to make that happen. You can stop the compiler from doing any rearranging by wrapping it in extern "C"{}, but even that will cause padding for alignment.
This claim sparked my curiosity, as I was taught that elements in structs can't be re-arranged, ever, in C or C++. So I investigated a bit. I found these two interesting answers:
http://stackoverflow.com/questions/9.../916691#916691
http://stackoverflow.com/questions/1.../118177#118177
 Originally Posted by C++ Section 9.2.12
Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (11.1)
 Originally Posted by C99 Section 6.7.2.1
Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared.
Long story short, it can't.
So yeah, that means the order of declaration can make a difference in the final struct size.
Unless you are on a very space-bound system though, I wouldn't worry too much about it, and declare elements in an order that makes sense to a human operator. And respect things like add new elements at the bottom, this makes it easier for change tacking.
Is your question related to IO?
Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|