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

zsa*_*yer 10 c types

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

像这样的东西:

void* type = (byte*);
Run Code Online (Sandbox Code Playgroud)

这是一个场景,我编写了一个测试用例并尝试使用某些数据类型打印出一个字节数组,以便在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);
}
Run Code Online (Sandbox Code Playgroud)

这看起来像效率低下的代码.我想象一下,可以将for-loop体的大小缩小到一行:

printf(format, ((type) expected)[i]);
Run Code Online (Sandbox Code Playgroud)

Yu *_*Hao 14

不,没有这种类型可以在标准C中存储类型.

gcc提供了一个typeof可能有用的扩展.使用此关键字的语法如下所示sizeof,但该构造在语义上与定义的类型名称相似typedef.详情请见此处.

更多使用示例typeof:

这声明了y与x指向的类型.

typeof (*x) y;
Run Code Online (Sandbox Code Playgroud)

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

typeof (*x) y[4];
Run Code Online (Sandbox Code Playgroud)

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

typeof (typeof (char *)[4]) y;
Run Code Online (Sandbox Code Playgroud)

它等同于以下传统的C声明:

char *y[4];
Run Code Online (Sandbox Code Playgroud)

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

#define pointer(T)  typeof(T *)
#define array(T, N) typeof(T [N])
Run Code Online (Sandbox Code Playgroud)

现在声明可以这样重写:

array (pointer (char), 4) y;
Run Code Online (Sandbox Code Playgroud)

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