可能重复:什么是 'unsigned temp:3' 的意思?
请问这种符号表示什么意思?
int a:16;
我发现代码里有这样的写法,而且可以编译。
struct name { int a:16; };
int a:16;
我发现代码里有这样的写法,而且可以编译。
struct name { int a:16; };
这是一个位域。
这个特定的位域并没有太多意义,因为你可以使用16位类型,而且由于位域被填充到int
的大小,所以浪费了一些空间。
通常情况下,你会在包含位大小元素的结构中使用它:
struct {
unsigned nibble1 : 4;
unsigned nibble2 : 4;
}
struct name { int a:16; }
这意味着a
被定义为16位的内存空间。剩余的位数(16位)从int
可以用来定义另一个变量,比如说b
,像这样:
struct name { int a:16; int b:16; }
如果int
是32位(4字节),那么一个int
的内存被分成两个变量a
和b
。
注:我假设sizeof(int)
= 4字节,1字节=8位。
struct s
{
int a:1;
int b:2;
int c:7;
};/*size of structure s is 4 bytes and not 4*3=12 bytes since all share the same space provided by int declaration for the first variable.*/
struct s1
{
char a:1;
};/*size of struct s1 is 1byte had it been having any more char _var:_val it would have been the same.*/