gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:34:28 24 4
gpt4 key购买 nike

这开始是一个玩笑类型的 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-infunction 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com