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

v-r*_*rob 2 c gcc typeof bit-fields

GNU C 有两个扩展,它建议制作安全的宏,MAX并且MIN只对参数求值一次:typeof__auto_type. 给出两个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;    \
})
Run Code Online (Sandbox Code Playgroud)

对于这两个问题是,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;
}
Run Code Online (Sandbox Code Playgroud)

GCC分别为typeof和提供了这些错误消息__auto_type

error: 'typeof' applied to a bit-field
error: '__auto_type' used with a bit-field initializer
Run Code Online (Sandbox Code Playgroud)

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

R..*_*R.. 6

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