In this lesson, you will learn about C function that implements call-by-value parameters. In C programming language, functions are very important because with functions there is no C program. The main () in C program is a function and it calls other user-defined functions. Some functions need parameters to do the necessary tasks.
So the efficiency of a program depends on how and what is passed as parameters to its functions when you call it in the main() function.
This program is written and compiled using Dev-C++ version 4 on a Windows 7 64-bit system. You can use any other standard C compiler to compile and run this program. This program is intended for beginner level learner of C programming.
Problem Definition
We mentioned earlier that you can call any function in the main() of a C program. There are two methods to call a function and pass parameters to the function.
- Call-by-Value
- Call-by-Reference
In this post, we will discuss only the functions that implements Call-by-Value method. The choice of method totally depends on the type of C program, so no particular method is superior to the other. To know more about call-by-reference, read the following article.
C Function that Implements Call-By-Reference
So when you call the function using call-by-value method and you pass actual arguments to the function. The copy of the original variable is sent to the function for processing. All operations are performed on the copy of the original value.
For example, if we declare two variables
int a = 10; /* Original values */
int b = 20; /* Original values */
Now, when the function is called in main ().
swap( a, b); /* Sends the copy of the original value of a and b */
In function swap () which contains the actual procedure of the function, uses the copy of variable values and perform operations defined within the function body.
void swap ( int a, int b) /* Use the copy of the original variable */
{
------------------------------
------------------------------
}
This method is a safe method because the original value will never get changed accidentally.
Flowchart – C function that implements Call-By-Value
Program Code
/* C Function that Implements Call-By-Value */
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,i;
void swap(int a,int b);
/* Read the integer values */
printf("ENTER TWO NUMBERS:");
scanf("%d%d",&a,&b);
for(i=0;i<45;i++)
printf("_");printf("\n\n");
printf("BEFORE SWAP: A =%dtB = %d\n",a,b);
for(i=0;i<45;i++)
printf("_");printf("\n\n");
/* Swap the integers */
for(i=0;i<45;i++)
printf("_");printf("\n\n");
swap(a,b); /* <-- function call using original variables */
for(i=0;i<45;i++)
printf("_");printf("\n\n");
getch();
return 0;
}
/* Swap operation */
void swap(int a,int b) /* <--- Parameters are copies of original variable values */
{
int temp = 0;
temp = a;
a = b;
b = temp;
/* Print the results */
printf("AFTER SWAP: A= %d\t B = %d\n",a,b);
}
Output
The output of the program is given below.