gpt4 book ai didi

c - 无符号整数位域移位产生有符号整数

转载 作者:太空狗 更新时间:2023-10-29 16:41:38 25 4
gpt4 key购买 nike

让我们考虑以下程序 test.c:

#include <stdio.h>

struct test {
unsigned int a:5;
};

int main () {
unsigned int i;
struct test t = {1};
for (i = 0; i < t.a << 1; i++)
printf("%u\n", i);
return 0;
}

当使用 gcc -Wsign-compare test.c 编译时,会产生以下警告(使用 gcc 4.8.1 测试):

test.c:9:19: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for (i = 0; i < t.a << 1; i++)
^

clang -Wsign-compare test.c 生成以下内容(使用 clang 3.2 测试):

test.c:9:19: warning: comparison of integers of different signs: 'unsigned int' and 'int' [-Wsign-compare]
for (i = 0; i < t.a << 1; i++)
~ ^ ~~~~~~~~
1 warning generated.

因此右操作数,一个移位的无符号位字段,变成了一个有符号的整数。此警告针对包含的 1 到 31 之间的任何位字段值显示。对于更高的值,不会产生警告。这很奇怪。

这是用 unsigned shortunsigned intunsigned long 类型的位域测试的。后者不显示包含 32 到 64 之间的位字段值的任何警告。

当没有完成移位时没有警告,因此位字段按预期无符号。

为什么小于 32 位的位字段在移位时变成有符号的?我认为这不是错误,因为这与 gccclang 一致。我一定是遗漏了一些关于位域(或移位)如何工作的信息,但是什么?移动无符号值如何产生有符号值?

最佳答案

整数提升应用于 draft C99 standard 中涵盖的移位操作数6.5.7 位移运算符 3 段说(强调我的前进):

The integer promotions are performed on each of the operands.[...]

位域的整数提升在 6.3.1.1 Boolean, characters, and integers2 中介绍:

The following may be used in an expression wherever an int or unsigned int may be used:

并包含以下项目符号:

A bit-field of type _Bool, int, signed int, or unsigned int.

然后说:

If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.48) All other types are unchanged by the integer promotions.

draft C11 中对此进行了澄清标准:

If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.58) All other types are unchanged by the integer promotions.

所以这是预期的行为。

关于c - 无符号整数位域移位产生有符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22152636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com