小编max*_*man的帖子

为什么即使有“if”语句,我的程序也不检查位域成员的值?

我编写了这个程序作为 C++ 中位域成员比较行为的测试用例(我想同样的行为也会在 C 中表现出来):

#include <cstdint>
#include <cstdio>

union Foo
{
    int8_t bar;
    struct
    {
#if __BYTE_ORDER == __LITTLE_ENDIAN
        int8_t baz : 1;
        int8_t quux : 7;
#elif __BYTE_ORDER == __BIG_ENDIAN
        int8_t quux : 7;
        int8_t baz : 1;
#endif
    };
};

int main()
{
    Foo foo;
    scanf("%d", &foo.bar);
    if (foo.baz == 1)
        printf("foo.baz == 1\n");
    else
        printf("foo.baz != 1\n");
}
Run Code Online (Sandbox Code Playgroud)

在我将其1作为输入编译并运行后,我得到以下输出:

foo.baz != 1
*** stack smashing detected ***: terminated
fish: “./a.out” terminated by signal SIGABRT …
Run Code Online (Sandbox Code Playgroud)

c c++ union signed bit-fields

2
推荐指数
2
解决办法
85
查看次数

标签 统计

bit-fields ×1

c ×1

c++ ×1

signed ×1

union ×1