Functions are called by their names Function call by value is the default way of calling a function Functions with arguments can be called by Reference Actual parameters: The parameters that appear in function calls. Formal parameters: The parameters that appear in function declarations.
Functions are called by their names.If the function does not have any arguments, then to call a function you can directly use its name. But for functions with arguments, we can call a function in two different ways, based on how we specify the arguments / parameter. These two ways are:
Before we discuss function call type, lets understand the terminologies that we will use while explaining this:
For example: We have a function declaration like this:
int sum(int a, int b);
The a and b parameters are formal parameters.
We call the function like this:
int s = sum(10, 20); //Here 10 and 20 are actual parameters
or
int s = sum(n1, n2); //Here n1 and n2 are actual parameters
Calling a function by value means, we pass the values of the arguments which are stored or copied into the formal parameters of the function. Hence, the original values are unchanged only the parameters inside the function changes.
#include<stdio.h>
void calc(int x);
int main()
{
int x = 10;
calc(x);
// this will print the value of 'x'
printf("\nvalue of x in main is %d", x);
return 0;
}
void calc(int x)
{
// changing the value of 'x'
x = x + 10 ;
printf("value of x in calc function is %d ", x);
}
Output
value of x in calc function is 20
value of x in main is 10
In call by reference we pass the address(reference) of a variable as argument to any function. When we pass the address of any variable as argument, then the function will have access to our variable, as it now knows where it is stored and hence can easily update its value.
In this case the formal parameter can be taken as a reference or a pointer, in both the cases they will change the values of the original variable.
#include<stdio.h>
void calc(int *p); // functin taking pointer as argument
int main()
{
int x = 10;
calc(&x); // passing address of 'x' as argument
printf("value of x is %d", x);
return(0);
}
void calc(int *p) //receiving the address in a reference pointer variable
{
/*
changing the value directly that is
stored at the address passed
*/
*p = *p + 10;
}
Output
value of x is 20