Objective-C: Compound Assignment Operators

Compound assignment operators are used by the developers in order to avoid lengthy statements for calculations. Some of them are listed below:

Compound Operators

Function

+=

Addition

– =

Subtratction

*=

Multiplication

/=

Division

%=

Modulo

Taking an example:

#import <Foundation/Foundation.h>

int main (int argc, const char *argv[])

{

 int a, b;

 a=5, b=4;

 a += b;   // using compound operator +=

 NSLog(@”Addtion using compound operator = %i”,a);

 a *= b;  // using compound operator *=

 NSLog(@”Multiplication using compound operator =    %i”,a);

 return 0;

}

 

Output:

Addition using compound operator = 9

Multiplication using compound operator = 36 

 

Typecasting in Objective-C

Typecasting is the method of converting one data type into another, from smaller data type to larger and vice-versa.

Typecast operator:  ( )

Typecasting is performed via the typecast operator denoted by ().

Example:

#import <Foundation/Foundation.h>

int main (int argc, const char *argv[])

{

 float a = 2.5;

 int b;

 b = (int)a; /* The float value of variable a is type-casted into  integer type b.*/

 NSLog(@”The value of b = %i”,b);

 return 0;

}


Another example for typecasting is shown here:

 

Explanation

In statement:        float d = (float) a;

The integer value of variable a is type-casted into float type of value, initially a stores an integer value but when a is type-casted to float type, the value of a=5 is converted into float type of value and is stored in the variable c = 5.000000.

Similarly, in statement:   int d = (int) b;

The float value of variable b is type-casted into integer type of value, initially b stores an float type of value but when b is type-casted to integer type, the value of b=3.500000 is converted into integer type  of value and is stored in the variable d = 3.

In statement:           int e = (int) 33333333333;

A double value is type-casted into an integer type. As the range of integer is smaller than double, the result is e = -1026405035.

Sizeof operator ( )

The sizeof operator in used to calculate the size of particular variable type in bytes, for example, consider the following program:

 

The above output shows, size of different data types in bytes.