开发者

IPhone SDK - How to detect variable type (float or double)?

How 开发者_开发百科do I detect whether a variable is float, double, int, etc.?

Thanks.


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).


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.


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));

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜