codescracker


objective c

Objective-C Type Casting



« Previous Tutorial Next Tutorial »


Type casting is a process to convert a variable from one data type to the another data type. For instance, if you want to store a value of long type into a simple integer, they you can cast the type long to int.

You can convert values from one data type to another data type explicitly using the cast operator like this:

(type-name) expression

In Objective-C Programming Language, we generally use CGFloat for doing floating-point operation, which is derived from the basic data type of float in case of 32-bit and double in case of 64-bit.

Objective-C Type Casting Example

Here is an example program, illustrates the type casting in Objective-C. Here the cast operator causes the division of one integer variable by the another to be performed as a floating-point operation:

/* Objective-C Type Casting - Example Program */
		
#import <Foundation/Foundation.h>
int main()
{
	int sum = 17, count = 5;
	CGFloat avg;
	
	mean = (CGFloat) sum / count;
	NSLog(@"Average = %f\n", avg);
	
	return 0;
}

When the above code is compile and executed, it will produce the following result:

2014-10-03 13:18:37.932 demo[20634] Average = 3.400000

As you can see from the above Objective-C program that the cast operator in Objective-C has precedence over the division, so the value of sum is first converted to the type double and then finally it gets divided by the count yielding a double value as you can see from the above output.

The type conversions can be implicit which is automatically performed by the compiler or it can be explicitly specified through the use of the cast operator in Objective-C.

Objective-C Integer Promotion

Integer promotion is a way by which, the values of integer type, smaller than int or unsigned int are converted either to int or to unsigned int. Here is an example program, of adding a character in an int, illustrates the concept of integer promotion in Objective-C:

/* Objective-C Type Casting - Example Program */
		
#import <Foundation/Foundation.h>
int main()
{
	int  num = 17;
	char c = 'c';	/* ascii value of c is 99 */
	int sum;
	
	sum = num + c;
	NSLog(@"Value of sum = %d\n", sum);
	
	return 0;
}

When the above code is compile and executed, it will produce the following result:

2014-10-03 13:18:37.932 demo[980] Value of sum = 116

Here, the value of the variable sum is coming as 116 because the Objective-C compiler is doing the integer promotion and converting the value of 'c' to ASCII (which is 99) before performing the actual addition operation.


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test