Typedef a bitfield variable

核能气质少年 提交于 2019-12-22 11:27:40

问题


I want to have a typedef that is 1-bit integer, so I though of this typedef int:1 FLAG; but I'm getting errors with it, is there a way I can do so? Thanks


回答1:


No.

The smallest addressable "thing" in a C Program is a byte or char.
A char is at least 8 bits long.
So you cannot have a type (or objects of any type) with less than 8 bits.

What you can do is have a type for which objects occupy at least as many bits as a char and ignore most of the bits

#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;
}

You can see the code above running at ideone.



来源:https://stackoverflow.com/questions/14536736/typedef-a-bitfield-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!