views:

49

answers:

4

Hello,

How do I detect whether a variable is float, double, int, etc.?

Thanks.

A: 

Some more info plz.. or use id Objects which can take any data type.. read this

KiranThorat
+4  A: 

Objective-C is not like PHP or other interpreted languages where the 'type' of a variable can change according to how you use it. All variables are set to a fixed type when they are declared and this cannot be changed. Since the type is defined at compile time, there is no need to query the type of a variable at run-time.

For example:

float var1; // var1 is a float and can't be any other type
int var2;  // var2 is an int and can't be any other type
NSString* var3;  // var3 is a pointer to a NSString object and can't be any other type

The type is specified before the variable name, also in functions:

- (void)initWithValue:(float)param1 andName:(NSString*)param2
{
    // param1 is a float
    // param2 is a pointer to a NSString object
} 

So as you can see, the type is fixed when the variable is declared (also you will notice that all variables must be declared, i.e. you cannot just suddenly start using a new variable name unless you've declared it first).

jhabbott
A: 

Use sizeof. For double it will be 8. It is 4 for float. double x = 3.1415; float y = 3.1415f; printf("size of x is %d\n", sizeof(x)); printf("size of y is %d\n", sizeof(y));

Pavel
This answer is not at all what the question was about and it does not allow you to distinguish between types with the same size.
jhabbott
A: 

In a compiled C based language (outside of debug mode with symbols), you can't actually "detect" any variable unless you know the type, or maybe guess a type and get lucky.

So normally, you know and declare the type before any variable reference.

Without type information, the best you can do might be to dereference a pointer to random unknown bits/bytes in memory, and hopefully not crash on an illegal memory reference.

Added comment:

If you know the type is a legal Objective C object, then you might be able to query the runtime for additional information about the class, etc. But not for ints, doubles, etc.

hotpaw2