c - 如何使用一个定义或函数使用 C 打印任何变量类型?

标签 c printing types c-preprocessor sizeof

这开始是一个玩笑类型的 Cython,我做了很多愚蠢的定义来使用 C 模拟 python。然后我意识到它实际上有点方便调试和快速组合程序。

我有一个大部分工作的定义,使用 sizeof 来区分类型,但是 3 或 7 个字符的 char 数组/字符串 + \0 将被打印为 double或一个整数。有没有办法解决?我正在考虑使用 try-exception 对其进行下标以查看它是否是字符串,但我无法实现。

#include <stdio.h>

#define print(n) if(sizeof(n)==8)      printf("%f\n",n); \
                 else if(sizeof(n)==4) printf("%i\n",n); \
                 else                  printf("%s\n",n); 

int main()
{
    print("Hello world!") // these all work perfectly
    print(8.93)
    print(4)

    print("abc") // these are interpreted as ints or doubles
    print("1234567")

    return 0;
}

最佳答案

gcc 有一个方便的内置功能(也可用于 clang),它允许直接比较类型:

int __builtin_types_compatible_p (type1, type2)

This built-in function returns 1 if the unqualified versions of the types type1 and type2 (which are types, not expressions) are compatible, 0 otherwise. The result of this built-in function can be used in integer constant expressions.

http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html

这个内置函数用于在 linux 内核中进行特定于类型的分派(dispatch)和类型检查,仅举一个例子。

要从表达式中获取类型,您可以依赖 typeof() 语句,顺其自然:

__builtin_types_compatible_p (typeof(n), int)

关于c - 如何使用一个定义或函数使用 C 打印任何变量类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23333227/

相关文章:

java - 如何在 Eclipse Java 调试器中将 char 数组显示为十六进制字节数组或无符号十进制数?

c - i686-w64-mingw32/include/shlobj.h 中的一些奇怪的代码

python - 以编程方式阻止特定文件(.txt 扩展名)的打印请求?

html - 打印时 CSS 样式丢失

python - 在 Python 中仅打印以逗号和空格分隔的列表中的数值

C 运行时类型检查

c - 如果字符可以容纳整数,那么为什么需要使用整数?

macOS 上的 Clang 无法从 ncurses 链接 lmenu

c++ - 使用#ifdefs 指定平台

c# - 泛型基类的派生类型