7

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) == typeof(int))
{
    // do something
}

Thanks in advance.

user464230
  • 876
  • 2
  • 11
  • 21
  • 4
    it's an int, you'll know by lookint at the source code - no need for reflection ! – nos Feb 26 '11 at 15:44
  • 2
    I do not really understand the question. If you define foo as an int, why would you need to get its type at compile time afterwards; introspection is useful in object-oriented programming to implement polymorphism, but I do not see why you would need it in C. – Greg Feb 26 '11 at 16:10
  • Such constructions would be useful to implement function overloading. – PintoDoido Apr 01 '19 at 16:25

5 Answers5

13

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.

sourcenouveau
  • 29,356
  • 35
  • 146
  • 243
  • Thanks, I've already imagine that. Something like #define MY_INT and later set another variable to hold my custom type, right? Thanks. – user464230 Feb 26 '11 at 15:45
  • 1
    or you could define a structure, where one field holds a "typeid" and the other field is larger enough to hold any value you might wish to store in the structure. – Jimmy Feb 26 '11 at 15:54
4

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

Jeff Ames
  • 2,044
  • 13
  • 18
2

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

Community
  • 1
  • 1
R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
1

Since C11, you can do that with _Generic:

if (_Generic(foo, int: 1, default: 0)) // if(typeof(foo)==int)
{
    // do something
}
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
0

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.

Jim Balter
  • 16,163
  • 3
  • 43
  • 66