c - 在 C 中使用 typeof 检查 typeof 变量
问题描述
我有一个我不输入的变量。所以要打印不知道是用%d
还是%f
。为此,我想在打印之前检查它的类型。
现在检查它的类型,我想像这样使用:
if (typeof(int) == voltage) {
snprintf(chars, sizeof(chars), "%d", voltage);
}
现在这是无效的。
我需要一种检查变量类型的方法。
我正在使用两个变量进行测试,但我认为以下也是无效的。
#define getIntType(a,b) ({ __auto_type _a = (a); __auto_type _b = (b); _a == typeof(int) ? _a : _b; });
int a = 10;
double b = 20.0;
int x = getIntType(a,b)==?; //How to call and how to store in type var of this x?
以及如何从宏中返回值/如何使用它?
#define typecheck(type,x) \
({ type __dummy; \
typeof(x) __dummy2; \
(bool)(&__dummy == &__dummy2); \
}) // How to return value to check?
//Then how to check?
int a = 10;
double b = 20.0;
//int x = getIntType(a,b)? a : b;
//bool isInt = typecheck(typeof(int), a);
解决方案
如果您想要一个可移植的解决方案,您可以查看 C11 通用宏,可怜的 C 程序员相当于 C++ 多态性:-)
以下程序显示了如何使用它:
#include <stdio.h>
#define Output(buff, sz, T) _Generic((T), \
char *: OutputS, \
double: OutputD, \
int: OutputI \
)(buff, sz, T)
void OutputS(char *buff, size_t sz, char *s) { snprintf(buff, sz, "S %s", s); }
void OutputD(char *buff, size_t sz, double d) { snprintf(buff, sz, "D %f", d); }
void OutputI(char *buff, size_t sz, int i) { snprintf(buff, sz, "I %d", i); }
int main() {
char buff[100];
Output(buff, sizeof(buff), "hello"); puts(buff);
Output(buff, sizeof(buff), 5); puts(buff);
Output(buff, sizeof(buff), 3.14159); puts(buff);
}
可以看到根据数据类型调用了正确的函数:
S hello
I 5
D 3.141590
推荐阅读
- javascript - 在 javascript 中使用 Pivotal API
- wpf - 填充数据网格后状态栏消失
- android - 应用程序 react-native-openalpr 在启动时崩溃
- android - 同时将日志输出到文件和系统日志
- angular - 如何解决引导角度 6 的问题
- javascript - 从 Javascript 模块中的父范围继承变量
- json - 无法使用 JSON.parse 解析 json 字符串?
- sql - 我想在访问 sql 中写一个 if else 语句,我确实写了一个代码,但它不工作
- azure - 无法在 Azure 分析服务中添加/连接 CosmosDB
- python-3.x - 无法从特定 python 路径创建 MSI 和 exe 文件