This blog is under construction

Saturday, 12 May 2012

Parameters passing

Parameters are the variables which are used to transfer values between the calling function and called function. 

Actual Arguments:
Arguments of the calling function are called actual arguments.

Formal Arguments:
Arguments of the called function are called formal arguments.

main() {
     fun(a, b);        // calling function with actual argument a and b

void fun(int x, int y) {  // called function with formal arguments x and y

There are two types of parameter passing schemes.  They are
1. pass by value
2. pass by reference

Pass by value:
A copy of actual arguments are passed to the formal arguments.  So, any modification to formal arguments won't affect the original value of actual arguments.

Pass by reference:
Here, the address of variables are passed from the actual argument to the formal argument.  So, the called function acts on addresses rather than values.  Here, the formal arguments have the pointer to the actual arguments. So, any change made to formal arguments would reflect on actual arguments.

We will see more about pass by value and pass by reference in next tutorial with some examples.

Example C program to illustrate parameter passing:
  #include <stdio.h>

  /* returns the sum value of given two numbers */
  int add(int a, int b) { //a and b are formal arguments
        return (a + b);

  int main() {
        int res, num1, num2;
        printf("Enter two integers: ");
        scanf("%d%d", &num1, &num2);// input two integers
        res = add(num1, num2);  // num1 & num2 are actual arguments
        printf("Sum of %d and %d is %d\n", num1, num2, res);
        return 0;

  jp@jp-VirtualBox:~/$ ./a.out
  Enter two integers: 10 20
  Sum of 10 and 20 is 30

No comments:

Post a Comment