Header Ads

Type Casting - Objective C

Type casting is a way to convert a variable from one data type to another data type. For example, if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another explicitly using the cast operator as follows:

(type_name) expression

In objective C we generally use CGFloat for doing floating point operation, which is derived from basic type of float in case 32 bit and double in case of  64 bit. Consider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating point operatiion.

#import <Foundation/Foundation.h>
int main()
{
       int sum = 17, count = 5;
       CGFloat mean;
      
       mean = (CGFloat) sum / count ;
       NSLog(@"Value of mean : %f\n", mean);

       return 0;
}

It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to type double and finally it gets  divided by count yeilding a double value/

Type conversions can be implicit which is performed by the compiler automatically or it can be specified explicitly through the use of the case operator. It is considered good programming practice to use the cast operator whenever type conversion are necessary.

Integer Promotion

Integer promotion is the process by which values of integer type "similar" than int or unsigned int are converted either to int or unsigned int. Consider an example of adding a character in an int.

#import <Foundation/Foundation.h>
int main()
{
       int s = 17;
      char cr = 'c';
      int sum;

       sum = s + c ;
       NSLog(@"Value of mean : %d\n", sum);

       return 0;
}

Here, value of sum is coming as 116 because compiler is doing integer promotion and converting the value of' 'c'  to ascii before performing actual addition operation.

Usual Arithmetic Conversion

The usual arithmetic conversions are implicitly performed to cast their values in a common type. Compiler first performs integer promotion. If operands still have different types then they are converted to the type .

The usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators && and || . Let us take following example to understand the concept:

#import <Foundation/Foundation.h>
int main()
{
       int s = 17;
      char cr = 'c';
      CGFloat sum;

       sum = s + c ;
       NSLog(@"Value of mean : %d\f", sum);

        return 0;
}

Here, it is simple to understand that first c gets converted to integer but because final value is float, so usual arithmetic conversion applies and compiler converts s and c into float and add then=m yielding a float result.

No comments:

Powered by Blogger.