Typedef一个位域变量

问题描述 投票:2回答:1

我想要一个1位整数的typedef,所以我虽然这个typedef int:1 FLAG;但是我遇到错误,有没有办法可以这样做?谢谢

c typedef bit-fields
1个回答
6
投票

没有。

C程序中最小的可寻址“事物”是字节或charchar至少8位长。 因此,您不能拥有少于8位的类型(或任何类型的对象)。

你可以做的是有一种类型,对象占用至少与char一样多的位,并忽略大部分位

#include <limits.h>
#include <stdio.h>

struct OneBit {
    unsigned int value:1;
};
typedef struct OneBit onebit;

int main(void) {
    onebit x;
    x.value = 1;
    x.value++;
    printf("1 incremented is %u\n", x.value);
    printf("each object of type 'onebit' needs %d bytes (%d bits)\n",
          (int)sizeof x, CHAR_BIT * (int)sizeof x);
    return 0;
}

您可以在ideone上看到上面的代码。

© www.soinside.com 2019 - 2024. All rights reserved.