首页 > 解决方案 > 在 C 中使用 typeof 检查 typeof 变量

问题描述

我有一个我不输入的变量。所以要打印不知道是用%d还是%f。为此,我想在打印之前检查它的类型。

现在检查它的类型,我想像这样使用:

if (typeof(int) == voltage) {
snprintf(chars, sizeof(chars), "%d", voltage);
}

现在这是无效的。

我需要一种检查变量类型的方法。

我正在使用两个变量进行测试,但我认为以下也是无效的。

以及如何使用我从这里这里获得并修改的这个 getIntType 函数/(它叫什么?宏?) ?

#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);

标签: ctypeof

解决方案


如果您想要一个可移植的解决方案,您可以查看 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

推荐阅读