Home arrow C and C+ arrow Parameter Passing in C
Parameter Passing in C PDF
Sunday, 26 April 2009
In C language when you call a function you can pass parameters by value or by reference.

Sending parameters by value
---------------------------------

example1.c
  1. #include <stdio.h>
  2.  
  3. int func1(int a);
  4.  
  5. int main(void)
  6. {
  7.   int i=100;
  8.  
  9.   printf("\nValue of i before calling func1 function: %d", i);
  10.   printf("\nValue returned by function func1: %d\n", func1(i));
  11. }
  12.  
  13. int func1(int a)
  14. {
  15.   printf("\nfunction was called!");
  16.   a = 120;
  17.   return a;
  18. }

Function will return 120. Please note that i does not change.


Sending parameters by reference (I)
-----------------------------------

example2.c
  1. #include <stdio.h>
  2.  
  3. void func2(int *x);
  4.  
  5. int main(void)
  6. {
  7.   int i=100;
  8.  
  9.   printf("\nValue of i before calling func2 function: %d", i);
  10.   func2(&i);
  11.   printf("\nValue of i after calling func2 function: %d\n", i);
  12. }
  13.  
  14. void func2(int *x)
  15. {
  16.   printf("\nfunction was called!");
  17.   *x = 140;
  18. }


Sending parameters by reference (II)
------------------------------------------

There is another way of sending parameters by reference that may look like parameters are send by value but it not. By sending an array as a parameter we will be able to reference the address of the array (knowing that if we have for example an array x[100], value x is the address of the first element in that array), and then in our function by changing values of elements from that array (function's formal parameters) we'll modify the array. See the following example:

example3.c
  1. #include <stdio.h>
  2.  
  3. void func3(int x[]);
  4.  
  5. int main(void)
  6. {
  7.   int i[5]={100,0,0,0,0};
  8.  
  9.   printf("\nValue of i[0] before calling func3 function: %d", i[0]);
  10.   func3(i);
  11.   printf("\nValue of i[0] after calling func3 function: %d\n", i[0]);
  12. }
  13.  
  14. void func3(int x[])
  15. {
  16.   printf("\nfunction was called!");
  17.   x[0] = 150;
  18. }


Notes
-------

 It is also possible to send variable to functions using global variables (variables defined at the beginning of a file, before main function, outside of any function).


Last Updated ( Sunday, 26 April 2009 )
 
< Prev   Next >

Other BSD Systems

OpenBSD

Misc

Solaris

Polls

Best BSD firewall?