sizeof and ternary operators in Objective-C

Advertisements


There are few other important operators including sizeof and ? : supported by Objective-C Language.

OperatorDescriptionExample
sizeof()Returns the size of a variable. sizeof(a), where a is interger, will return 4.
&Returns the address of a variable.&a; will give actual address of the variable.
*Pointer to a variable.*a; will pointer to a variable.
? :Conditional Expression If Condition is true ?, Then value X : Otherwise value Y

Example

Try the following example to understand all the miscellaneous operators available in Objective-C programming language:

#import <Foundation/Foundation.h>

main()
{
   int a = 4;
   short b;
   double c;
   int* ptr;

   /* example of sizeof operator */
   NSLog(@"Line 1 - Size of variable a = %d\n", sizeof(a) );
   NSLog(@"Line 2 - Size of variable b = %d\n", sizeof(b) );
   NSLog(@"Line 3 - Size of variable c= %d\n", sizeof(c) );

   /* example of & and * operators */
   ptr = &a;	/* 'ptr' now contains the address of 'a'*/
   NSLog(@"value of a is  %d\n", a);
   NSLog(@"*ptr is %d.\n", *ptr);

   /* example of ternary operator */
   a = 10;
   b = (a == 1) ? 20: 30;
   NSLog(@"Value of b is %d\n", b );

   b = (a == 10) ? 20: 30;
   NSLog(@"Value of b is %d\n", b );
}

When you compile and execute the above program, it produces the following result:

2013-09-07 22:46:22.702 demo[24593] Line 1 - Size of variable a = 4
2013-09-07 22:46:22.703 demo[24593] Line 2 - Size of variable b = 2
2013-09-07 22:46:22.703 demo[24593] Line 3 - Size of variable c= 8
2013-09-07 22:46:22.703 demo[24593] value of a is  4
2013-09-07 22:46:22.703 demo[24593] *ptr is 4.
2013-09-07 22:46:22.703 demo[24593] Value of b is 30
2013-09-07 22:46:22.703 demo[24593] Value of b is 20


Advertisements
Advertisements