What is type casting in Objective-C?
Overview
Type casting in Objective-C is the activity of converting a variable from one data type to another.
For instance, we can use type casting to convert the double data type to int, and vice versa. We can do this explicitly with the help of cast operators.
Syntax
Here is the basic syntax of type casting through the cast operator.
(type_name) expression
Example
We utilize CGFloat to perform the operations regarding floating points in Objective-C. An example related to floating-point operations is as follows:
#import <Foundation/Foundation.h>int main() {NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];int num1 = 78, num2 = 2;CGFloat ans;// division operationans = (CGFloat) num1 / num2;NSLog(@"The answer is : %f\n", ans );[pool drain];return 0;}
Explanation
In the example above, the cast operator has precedence over the division. That’s why num1 is converted to type double and divided by num2.
Type casting cases
There are two cases in type casting: implicit and explicit.
- Implicitly, type casting is done automatically by the compiler.
- Explicitly, the cast operator converts the data type of a variable.
Integer promotion
In integer promotion, the values of DataType integers that are smaller than unsigned int or int are type casted into int or unsigned int.
Example
Let’s discuss an example of integer promotion.
#import <Foundation/Foundation.h>int main() {NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];int n = 10;char b = 'b'; /* ascii code is 98 */int ans;/* int and char values addition */ans = n + b;NSLog(@"The answer is : %d\n", ans);[pool drain];return 0;}
Explanation
In the code above, the ans is 108 due to the implementation of the integer promotion. The value of b is converted to ASCII, and then the addition operation is performed.
Usual arithmetic conversion
Usual arithmetic conversion is an implicit conversion of operands in a common DataType.
If the operands still have dissimilar data types even after the implementation of integer promotion, then the usual arithmetic conversion is performed.
It can be done by converting the value to the type that displays on the top of the below-mentioned hierarchy.
Usually, arithmetic conversions cannot be performed for logical operators e.g., &&, || and assignment operators.
Example
Let’s discuss an example regarding usual arithmetic conversions.
#import<Foundation/Foundation.h>int main() {int n = 10;char b = 'b'; /* ascii code is 98 */CGFloat ans;ans = n + b;printf("The answer is: %f\n", ans);return 0;}
Explanation
In the code above, b is first converted to an integer, but the conversion applies because ans is of float type. So, n and b are converted to float. Then, the float result of the addition operation is provided.