作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
GNU C 有两个扩展,它建议制作安全的宏,如 MAX
和 MIN
,它们只会对参数求值一次: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/
我一直在用__auto_type在 C 中使用了一段时间,我想知道它是否与 auto 有任何不同在 C++ 中。它们的实现方式不同吗? 我试过搜索这个,但它没有产生任何结果,因为搜索 C 中的 __a
GNU C 有两个扩展,它建议制作安全的宏,如 MAX 和 MIN,它们只会对参数求值一次:typeof 和 __自动类型。举两个 MAX 宏的例子来演示每个宏: #define MAX(a, b)
我是一名优秀的程序员,十分优秀!