0

Why would the following things be advisable?
Prefer a plain int over a short int or a long int.
Prefer a double over a float or a long double.
Prefer plain char over signed char and unsigned char.

Why ordering members of a struct by size can minimize wasted space on certain machines?

Thank you very much!!:)

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by Narue
0

>Prefer a plain int over a short int or a long int.
int (as opposed to short int or long int) has traditionally been the "natural" integer size for the platform. Using this "natural" integer size gives more leeway for optimization at both the implementation level and the platform level.

>Prefer a double over a float or a long double.
double is the default floating-point type. Unless you're really strapped for space, float is quite pointless. long double on the other hand can be expensive if it's larger and you don't use the extra precision, and on some platforms (*cough*Windows*cough*) long double is the same size as double. In the latter case, you've added the complexity of a non-default type without the benefit of greater precision.

>Prefer plain char over signed char and unsigned char.
If you're using char as a character type, this is absolutely essential. Vanilla char can be either signed or unsigned depending on your implementation, and using the wrong signedness can wreak havoc. If you're using char as a small integer type, follow the same rules as int for choosing between signed and unsigned. If you're using char for type punning, go unsigned.

>Why ordering members of a struct by size can minimize wasted space on certain machines?
It's all about alignment. For simplicity sake let's say that char can be aligned on any byte but a four byte int must be aligned at multiples of 4. Now consider this structure declaration:

struct foo {
  char a;
  int b;
} bar;

Let's say that bar is assigned to address 0. That means bar.a is also at address 0, but because bar.b is an int, it must be aligned on a multiple of 4. Therefore bar.b is at address 4 so addresses 1, 2, and 3 are wasted to fit bar.b at the right alignment:

+=====+
0|bar.a|
 +-----+
1|xxxxx|
 +-----+
2|xxxxx|
 +-----+
3|xxxxx|
 +-----+
4|bar.b|
 +-----+
5|bar.b|
 +-----+
6|bar.b|
 +-----+
7|bar.b|
 +=====+

Now consider what happens when you swap the two members:

struct foo {
  int a;
  char b;
} bar;

Now a is aligned to 0 and takes up four bytes. Remembering that char can be aligned on any address, there are no longer any wasted bytes:

+=====+
1|bar.a|
 +-----+
2|bar.a|
 +-----+
3|bar.a|
 +-----+
4|bar.a|
 +-----+
5|bar.b|
 +=====+
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.