在C语言中,int a:16;的意思是什么?

12
4个回答

19

这是一个位域

这个特定的位域并没有太多意义,因为你可以使用16位类型,而且由于位域被填充到int的大小,所以浪费了一些空间。

通常情况下,你会在包含位大小元素的结构中使用它:

struct {
    unsigned nibble1 : 4;
    unsigned nibble2 : 4;
}

14
struct name { int a:16; }

这意味着a被定义为16位的内存空间。剩余的位数(16位)从int可以用来定义另一个变量,比如说b,像这样:

struct name { int a:16;  int b:16; }

如果int是32位(4字节),那么一个int的内存被分成两个变量ab

注:我假设sizeof(int) = 4字节,1字节=8位。


4
 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.*/

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接