typedef union bit-field

1. typedef

typedef struct tnode *Treeptr;

typedef struct tnode {
    char *word;
    int count;
    struct tnode *left;
    struct tnode *right;
} Treenode; 

/* Treenode (a structure) and Treeptr (a pointer to the structure). */

typedef int (*PFI)(char *, char *);

/* creates the type PFI, for “pointer to function (of two char * arguments) returning int,” */

2. union

A union is a variable that may hold (at different times) objects of different types and sizes,
with the compiler keeping track of size and alignment requirements.

union u_tag {
int ival;
float fval;
char *sval;
} u;

In effect, a union is a structure in which all members have offset zero from the base,
the structure is big enough to hold the “widest” member.

A union may only be initialized with a value of the type of its first member;
thus union u described above can only be initialized with an integer value.

3. bit-field

struct {
    unsigned int is_keyword : 1;
    unsigned int is_extern : 1;
    unsigned int is_static : 1;
} flags;

This defines a variable table called flags that contains three 1-bit fields.
The number following the colon represents the field width in bits.

They are not arrays and they do not have addresses, so the & operator cannot be applied on them.

// example.c

struct {
    unsigned char a : 1;
    unsigned char b : 5;
    unsigned char c : 3;
} bs;

#include <stdio.h>
int main ()
{
    bs.a = 1;
    bs.b = 30;
    bs.c = 9;
    printf("%d,%d,%d,%d\n", sizeof (bs), bs.a, bs.b, bs.c);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值