Passing arguments to functions in C language
In C language, arguments can be passed to functions in two ways: by value and by reference.
Pass by Value:
By passing arguments by value, the function receives a copy of the parameter value. This indicates that any modifications made to the argument inside the function have no impact on the argument’s initial value outside the function.
Syntax of pass by value:
return_type function_name(data_type parameter_name)
{
// Function body
}
Example:
#include <stdio.h>
void change_value(int x) {
x = 10;
}
int main() {
int num = 5;
printf("Before function call, num = %d\n", num);
change_value(num);
printf("After function call, num = %d\n", num);
return 0;
}
Output:
Before function call, num = 5
After function call, num = 5
In the above example, change value function takes an argument x by value. When num is passed to this function, a copy of num with the value 5 is made and passed to the function. Any changes made to x inside the function do not affect the original value of num outside the function.
Pass by Reference:
The address of the argument is supplied to the function when arguments are passed by reference. This implies that any modifications made to the argument inside the function have an impact on the argument’s initial value outside the function.
Syntax of pass by reference:
void functionName(dataType *arg) {
/* function body */
}
int main() {
dataType variableName;
functionName(&variableName); /* passing variable by reference */
/* rest of the code */
return 0;
}
Example:
#include <stdio.h>
void change_value(int *x) {
*x = 10;
}
int main() {
int num = 5;
printf("Before function call, num = %d\n", num);
change_value(&num);
printf("After function call, num = %d\n", num);
return 0;
}
Output:
Before function call, num = 5
After function call, num = 10
In the above example, change value function takes an argument x by reference using a pointer. When &num is passed to this function, the address of num is passed instead of the value. Any changes made to *x inside the function affect the original value of num outside the function.