C Pointers And Functions

In this tutorial, you will learn about the use of pointers for calling and implementing functions. We can also name this process as call by reference. It is not mandatory that you can only pass variables and values to the function whereas you can also pass the addresses. Whenever we pass the address to a function, we must specify pointers in the function definition. Which means that the parameters receiving the address must be pointers. The functions that implement the call by reference can change the value of the variables which are used in the function call. Any changes that the user makes on the reference variable will affect the original variable.

Please go through the following example which will make you understand more about the call by reference in C.

Example illustrating the Function call by reference in C.

In the example below, we will be using pointers and addresses of the variables for implementing the functions in our program. Here, the main goal of this program below is to swap two numbers in the program. I this sort of examples, It is not possible to swap numbers using the call by value. Hence, we apply the call by reference in such programs as we are going to change the reference variable. The same changes must be displayed in the original variable too. Therefore, pointers come adds the beauty on C by offering flexibility and features in such a way.

Code:

#include<stdio.h>
void swap(int*, int*);//Function Prototype
int main(){
	int a=10, b=20;
	printf("a= %d\t b=%d \n", a,b);
	swap(&a, &b);//Fucntion call by the addresses of the variables
	printf("After swapping the result will become: \n");
	printf("a=%d\t b=%d", a,b);
}
void swap(int *p, int *q){ //Fucntion definition having the pointers of the varibles in the parameter.
	int t;
	t=*p;
	*p=*q;
	*q=t;
}

Output

a= 10                b= 20
After swapping the result will become:
a= 20               b= 10
SHARE C Pointers And Functions

You may also like...

Leave a Reply

Your email address will not be published.

Share