The following is the source code of a function called max(). This function takes two parameters num1 and num2, and returns the largest of the two?
“`
// function returning the max between two numbers
int max(int num1, int num2) {
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
“`
Calling A Function
When we have a function in a program, depending on the requirement, we need to call or invoke that function. When a function is called or invoked, it executes its set of instructions to provide the desired results.
The function can be called from anywhere in the program. It can be called from the prior function or any other function if the program uses more than one function. A function that calls another function is called a “calling function”.
For Example-
“`
#include
using namespace std;
// function declaration
int max(int num1, int num2);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
ret = max(a, b);
cout << “Max value is: ” << ret << endl;
return 0;
}
// function returning the max between two numbers
int max(int num1, int num2) {
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
“`
Here, the max() function and the main() function are compiled into the source code. While running the final executable, it would produce the following result-
“`
Max value is: 200
“`
There are two most common methods to call functions in c++:
1. Call by Value:
In this call method, you pass only a copy of the variable to the function, not the actual argument. When specifying variable or argument documents, any changes made to a variable in a function do not affect the actual argument.
For Example-
“`
void calc(int x);
int main()
{
int x = 10;
calc(x);
printf(“%d”, x);
}
void calc(int x)
{
x = x + 10 ;
return x;
}
“`
Output
“`
20
“`
2. Call by Reference:
In this calling technique, you pass the address or reference of an argument, and the function receives the memory address of the argument. In this case, the value of the variable changes, or you can say it reflects the changes back to the actual variable.
For Example-
“`
void calc(int *p);
int main()
{
int x = 10;
calc(&x); // passing address of x as argument
printf(“%d”, x);
}
void calc(int *p)
{
*p = *p + 10;
}
“`
Output
“`
20
“`
Conclusion
After reading this blog on C++ functions, you will understand why you use functions in C++, what a function in C++, its syntax, and the types of functions in C++. You have also learned about function calling methods, i.e., call by value and call by reference, with the help of some examples.