10_Objective-C Type Casting

Type casting is a way to convert a variable from one data type to another data type.

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.

(type_name) expression 

Example where the cast operator causes the division of one integer variable by another to be performed as a floating-point operation

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 yielding 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 cast operator.

It is considered good programming practice to use the cast operator whenever type conversions are necessary.

Integer Promotion

Integer promotion is the process by which values of integer type “smaller” than int or unsigned int are converted either to int or unsigned int.

Example of adding a character in an int

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 that appears highest in the following hierarchy:

  • Int
  • Unsigned int
  • Long
  • Unsigned long
  • Long long
  • Unsigned long long
  • Float
  • Double
  • Long double

The usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators && and ||. Let us

Example to understand the concept

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 i and c into float and add them yielding a float result.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s