Pass By Reference In C

Passing by reference is a technique for passing parameters to a function. It is also known as call by reference, call by pointers, and pass by pointers. In this article, we will discuss this technique and how to implement it in our C program.

Pass By Reference in C

In this method, the address of an argument is passed to the function instead of the argument itself during the function call. Due to this, any changes made in the function will be reflected in the original arguments. We use the address operator (&) and indirection operator (*) to provide an argument to a function via reference.

When any argument is passed by reference in the function call as a parameter, it is passed using the address of(&) operator from the main function. In the function definition, the function takes the value of the parameter by using (*) operator. By using this, it can directly access the value of the parameter directly from its original location. There will be no need for extra memory or copying the same data into some other fields.

Also, a pointer type must be defined for the matching parameter in the called function in C.

Syntax

The code will look like this in the pass-by-reference method:

// function definion return_type functionName (arg_type *arg1, arg_type *arg1, . ) < // function body > . . // function call functionName (&arg1, &arg2, . );

Example of Pass by Reference

In the below program, the arguments that are passed by reference will be swapped with each other.