Could I retrieve the datatype from a variable in C?

后端 未结 5 1827
灰色年华
灰色年华 2020-12-11 05:42

Has a way to get the datatype in C?

For example:

int foo;

if (foo is int)
{
    // do something
}

or something like:

if (typeof(foo         


        
相关标签:
5条回答
  • 2020-12-11 06:17

    There is a typeof extension in GCC, but it's not in ANSI C: http://tigcc.ticalc.org/doc/gnuexts.html#SEC69

    0 讨论(0)
  • 2020-12-11 06:24

    The fact that foo is an int is bound to the name foo. It can never change. So how would such a test be meaningful? The only case it could be useful at all is in macros, where foo could expand to different-type variables or expressions. In that case, you could look at some of my past questions related to the topic:

    Type-generic programming with macros: tricks to determine type?

    Determining presence of prototype with correct return type

    0 讨论(0)
  • 2020-12-11 06:26

    Since C11, you can do that with _Generic:

    if (_Generic(foo, int: 1, default: 0)) // if(typeof(foo)==int)
    {
        // do something
    }
    
    0 讨论(0)
  • 2020-12-11 06:41

    The only time you wouldn't know the type is if the type of foo is defined by a typedef -- if that's the case, your example should reflect it. And why do you need to something dependent on the type? There may well be a way to solve your actual problem, but you haven't presented your actual problem.

    0 讨论(0)
  • 2020-12-11 06:44

    This is called type introspection or reflection and is not supported by the C language. You would probably have to write your own reflection library, and it would be a significant effort.

    0 讨论(0)
提交回复
热议问题