我找到了这段代码,我明白它的作用(如果 var 是浮点类型,则打印),但我不明白如何:
#include <stdio.h>
#include <stdlib.h>
#define typename(x) _Generic((x), float: "float")
#define isCompatible(x, type) _Generic(x, type: true, default: false)
int main(){
float var;
if(isCompatible(var, float))
printf("var is of type float!\n");
}
什么是 typename(x) ?为什么从不调用?
我也无法理解这个结构:
_Generic(x, type: true, default: false)
这里有一种方法可以不将 float 作为参数传递并使其隐式吗?
if(isCompatible(var, float))
最佳答案
我怀疑您想查看 _Generic
here 的文档 - 它是 C11 功能(C11 标准 (ISO/IEC 9899:2011) s 6.5.1.1 Generic selection (p: 78-79))。另请参阅已接受的答案 here 。
本质上,在这个例子中, isCompatible
宏调用 _Generic
并且(通过 type: true
)返回 true
如果 x
(第一个参数)与类型 type
兼容,否则 false
。
宏 typename
未使用,但如果参数与 float
兼容,则返回文本 float
。为什么有定义但没有使用的东西,你必须问代码的作者。
关于c - 使用宏进行类型检查,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50433763/