c - 是否可以将 C 数据类型存储在变量中?

标签 c types

是否可以在变量中存储 C 数据类型?

是这样的:

void* type = (byte*);

这是一个场景,我编写了一个测试用例,并尝试使用某些数据类型打印出一个字节数组以供 printf 使用,具体取决于给定的参数:

void print_byteArray(const void* expected, size_t size, 
        bool asChars, bool asWCharT) {
    int iterations;
    char* format;
    if (asChars) {
        iterations = (size / (sizeof (char)));
        format = "%c";
    } else if (asWCharT) {
        iterations = (size / (sizeof (wchar_t)));
        format = "%lc";
    } else {
        iterations = (size / (sizeof (byte)));
        format = "%x";
    }
    int i;
    for (i = 0; i < iterations; i++) {
        if (asChars) {
            printf(format, ((char*) expected)[i]);
        } else if (asWCharT) {
            printf(format, ((wchar_t*) expected)[i]);
        } else {
            printf(format, ((byte*) expected)[i]);
        }
    }
    fflush(stdout);
}

这看起来像是低效的代码。我想可以将 for 循环体缩小到一行:

printf(format, ((type) expected)[i]);

最佳答案

不,不存在可以在标准 C 中存储类型的类型。

gcc 提供了一个可能有用的 typeof 扩展。使用此关键字的语法看起来像 sizeof,但结构在语义上就像用 typedef 定义的类型名称。参见 here了解详情。

使用 typeof 的更多示例:

这用 x 指向的类型声明了 y。

typeof (*x) y;

这将 y 声明为此类值的数组。

typeof (*x) y[4];

这将 y 声明为指向字符的指针数组:

typeof (typeof (char *)[4]) y;

它等价于下面的传统 C 声明:

char *y[4];

要查看使用 typeof 的声明的含义,以及为什么它可能是一种有用的编写方式,请使用这些宏重写它:

#define pointer(T)  typeof(T *)
#define array(T, N) typeof(T [N])

现在可以这样重写声明:

array (pointer (char), 4) y;

因此,array (pointer (char), 4) 是 4 个指向 char 的指针的数组类型。

关于c - 是否可以将 C 数据类型存储在变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17645224/

相关文章:

c# - 转换数据结构

c - 检查字符串是否回文时出错

C、无法读取输入

JAVASCRIPT 数据类型问题

javascript - 我可以使用 constructor.name 来检测 JavaScript 中的类型吗

typescript - 如何在 Typescript 中对相关属性进行建模

C - 连接函数 - 无效参数错误

Python 不确定性 Unumpy 类型错误?

dynamic - 在 Kotlin 中如何声明可以是字符串或函数的函数参数?

c - 修改一个字符指针?