How to save the result of typeof? [closed]

流过昼夜 提交于 2019-12-13 07:24:14

问题


I am a new programmer that is mostly using Code::Blocks for C99. I recently found out about the typeof() because it was hidden as __typeof __() and I wanted to know if you can save a type as a result of typeof. something like:

type a = __typeof__(?); 

Or

#define typeof __typeof__
type a = typeof(?);

Is this possible?


回答1:


You should avoid typeof or __typeof __() since they aren't standard C. The latest C version (C11) has support for this through the _Generic keyword which works in the same manner.

There is no "type type" in C but you can easily make one yourself:

typedef enum
{
  TYPE_INT,
  TYPE_FLOAT,
  TYPE_CHAR
} type_t;

#define get_typeof(x)   \
  _Generic((x),         \
    int:   TYPE_INT,    \
    float: TYPE_FLOAT,  \
    char:  TYPE_CHAR );

...

float f;
type_t type = get_typeof(f);



回答2:


No, you can not use typeof like t = (typeof(x) == int) ? a : b; nor int t = typeof(x); .

If you are under C11, _Generic can help:

#include <stdio.h>

enum {TYPE_UNKNOWN, TYPE_INT, TYPE_CHAR, TYPE_DOUBLE};

#define type_of(T) _Generic((T), int: TYPE_INT, char: TYPE_CHAR, double: TYPE_DOUBLE, default: 0)

int main(void)
{
    double a = 5.;
    int t = type_of(a);

    switch (t) {
        case TYPE_INT:
            puts("a is int");
            break;
        case TYPE_CHAR:
            puts("a is char");
            break;
        case TYPE_DOUBLE:
            puts("a is double");
            break;
        default:
            puts("a is unknown");
            break;
    }
    return 0;
}


来源:https://stackoverflow.com/questions/42222379/how-to-save-the-result-of-typeof

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!