ADVERTISEMENT
ADVERTISEMENT

Methods of Parameter Passing in C with Examples

In C, there are three main methods of parameter passing: call by value, call by reference, and call by pointer.

  • Call by Value: In this method, the actual value of the parameter is passed to the function. Any changes made to the parameter within the function have no effect on the argument outside the function.

  • Call by Reference: In this method, the address of the parameter is passed to the function. Any changes made to the parameter within the function are reflected in the argument outside the function. This is done by passing a reference to the memory location of the variable, rather than its value.

  • Call by Pointer: This method is similar to call by reference, but it uses pointer variables to pass the memory address. The function receives a pointer to the variable, which it can then dereference to access the value stored at that memory location.

Call By Value

"Call by value" is a technique for passing arguments to a function in C programming. The actual value of the argument is passed to a function when it is called by value. As a result, any modifications made to the argument within the function have no impact on the argument's initial value within the calling function.

The syntax for calling a function by value is the same calling a function with any other method.. For instance, you would type "foo(x);" to invoke a function with the argument "x."

Here is a C programme example that demonstrates the idea of call by value:

#include <stdio.h>
void swap(int,int);  //Declaration
int main()
 {
    int a = 10, b = 20;
    printf("Before swap, a = %d, b = %d", a, b);
    swap(a, b);    //Calling
    printf("After swap, a = %d, b = %d", a, b);
    return 0;
}

void swap(int x, int y)    // Definition
{
    int temp = x;
    x = y;
    y = temp;
}

In this example, the function "swap" simply performs a swap operation on the two arguments it receives, "x" and "y." Two variables "a" and "b" are initially initialised by the main() function with values of 10 and 20, respectively. The swap() function is then invoked with the arguments "a" and "b". Before and after the function call, the programme prints the values of "a" and "b."

The programme will print "Before swap, a = 10, b = 20" and "After swap, a = 10, b = 20" when it has finished running. This demonstrates that the swap function has no impact on the values of "a" and "b" because it uses copies of the values rather than the original variables.


ADVERTISEMENT

ADVERTISEMENT