gpt4 book ai didi

c - 应用于位字段的 typeof/__auto_type 的 GNU C 替换/解决方法

转载 作者:行者123 更新时间:2023-12-05 08:50:02 25 4
gpt4 key购买 nike

GNU C 有两个扩展,它建议制作安全的宏,如 MAXMIN,它们只会对参数求值一次:typeof__自动类型。举两个 MAX 宏的例子来演示每个宏:

#define MAX(a, b) ({    \
typeof(a) _a = (a); \
typeof(b) _b = (b); \
_a > _b ? _a : _b; \
})

#define MAX(a, b) ({ \
__auto_type _a = (a); \
__auto_type _b = (b); \
_a > _b ? _a : _b; \
})

这两个的问题是 typeof__auto_type 如果用在位字段上会出错。此示例代码显示了使用 MAX 的位域的问题:

#include <stdio.h>
#include <stdint.h>

// Insert one of the MAX macros here

struct bitfields {
uint8_t a: 4;
uint8_t b: 4;
};

int main(int argc, char *args[]) {
struct bitfields x = {12, 4};
printf("%d\n", MAX(x.a, x.b));
return 0;
}

GCC 分别为 typeof__auto_type 给出这些错误消息:

error: 'typeof' applied to a bit-field
error: '__auto_type' used with a bit-field initializer

所以问题是:为什么 GCC 不允许这些与位字段一起使用(我找不到任何关于它的文档),以及如何制作一个 MAX 宏仅对仍可与位字段一起使用的任何类型评估参数一次?

最佳答案

您使用 __typeof__(+(a)) 根据默认促销获取促销类型。这至少适用于 int 类型的位域。我不确定编译器如何处理更大的位域类型的类型,这些类型是实现定义的。

关于c - 应用于位字段的 typeof/__auto_type 的 GNU C 替换/解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62865732/

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