在结构安排领域哪种方式更好? [英] Which way of arranging fields in structure is better?
本文介绍了在结构安排领域哪种方式更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两种方法来安排结构中的字段
I have two ways to arrange the fields in a structure
struct foo {
float a;
double b;
float c;
double d;
short e;
long f;
short g;
long h;
char i;
int j;
char k;
int l;
};
struct foo {
double b;
double d;
long f;
long h;
float a;
float c;
int j;
int l;
short e;
short g;
char i;
char k;
};
哪一个应实行为什么?
Which one should be practiced and why?
推荐答案
来安排结构成员的最好办法是把他们在递增顺序,通过它们的大小。 这样做,可以减少填充 ,需要数据对齐。
The best way to arrange members of a structure is to put them in increasing order, by their size. Doing this, you reduce the padding, required for data alignment.
此外,使用一些 preprocessor指令你修改对齐,例如:
Also, using some preprocessor directives you modify the alignment, for example:
#define packed_data __attribute__((__packed__))
将其关闭。用这种方法,成员为了此事doesen't了,但我坚决取缔这种做法,因为内存alingnment的性能得到优化。
turns it off. Using this, the member order doesen't matter anymore, but I strongly discourage this, as the memory alingnment is optimised for performance.
这篇关于在结构安排领域哪种方式更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文