Function call by value in Objective-C



The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

By default, Objective-C programming language uses call by value method to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function. Consider the function swap() definition as follows −

/* function definition to swap the values */
- (void)swap:(int)num1 andNum2:(int)num2 {
   int temp;

   temp = num1;   /* save the value of num1 */
   num1 = num2;   /* put num2 into num1 */
   num2 = temp;   /* put temp into num2 */
  
   return;
}

Now, let us call the function swap() by passing actual values as in the following example −

#import <Foundation/Foundation.h>

@interface SampleClass:NSObject
/* method declaration */
- (void)swap:(int)num1 andNum2:(int)num2;
@end

@implementation SampleClass

- (void)swap:(int)num1 andNum2:(int)num2 {
   int temp;

   temp = num1;   /* save the value of num1 */
   num1 = num2;   /* put num2 into num1 */
   num2 = temp;   /* put temp into num2 */
   
}

@end

int main () {
   
   /* local variable definition */
   int a = 100;
   int b = 200;
   
   SampleClass *sampleClass = [[SampleClass alloc]init];

   NSLog(@"Before swap, value of a : %d\n", a );
   NSLog(@"Before swap, value of b : %d\n", b );
 
   /* calling a function to swap the values */
   [sampleClass swap:a andNum2:b];
 
   NSLog(@"After swap, value of a : %d\n", a );
   NSLog(@"After swap, value of b : %d\n", b );
 
   return 0;
}

Let us compile and execute it, it will produce the following result −

2013-09-09 12:12:42.011 demo[13488] Before swap, value of a : 100
2013-09-09 12:12:42.011 demo[13488] Before swap, value of b : 200
2013-09-09 12:12:42.011 demo[13488] After swap, value of a : 100
2013-09-09 12:12:42.011 demo[13488] After swap, value of b : 200

Which shows that there is no change in the values though they had been changed inside the function.

objective_c_functions.htm
Advertisements