Functions are used to provide modularity to a program. Creating an application using function makes it easier to understand, edit, check errors etc.
Here is how you define a function in C++,
return-type function-name(parameter1, parameter2, ...)
{
// function-body
}
// function for adding two values
void sum(int x, int y)
{
int z;
z = x + y;
cout << z;
}
int main()
{
int a = 10;
int b = 20;
// calling the function with name 'sum'
sum (a, b);
}
Here, a
and b
are two variables which are sent as arguments to the function sum
, and x
and y
are parameters which will hold values of a
and b
to perform the required operation inside the function.Function declaration, is done to tell the compiler about the existence of the function. Function's return type, its name & parameter list is mentioned. Function body is written in its definition. Lets understand this with help of an example.
#include < iostream>
using namespace std;
//declaring the function
int sum (int x, int y);
int main()
{
int a = 10;
int b = 20;
int c = sum (a, b); //calling the function
cout << c;
}
//defining the function
int sum (int x, int y)
{
return (x + y);
}
Here, initially the function is declared, without body. Then inside main()
function it is called, as the function returns sumation of two values, and variable c
is there to store the result. Then, at last, function is defined, where the body of function is specified. We can also, declare & define the function together, but then it should be done before it is called.
Functions are called by their names. If the function is without argument, it can be called directly using its name. But for functions with arguments, we have two ways to call them,
In this calling technique we pass the values of arguments which are stored or copied into the formal parameters of functions. Hence, the original values are unchanged only the parameters inside function changes.
void calc(int x);
int main()
{
int x = 10;
calc(x);
printf("%d", x);
}
void calc(int x)
{
x = x + 10 ;
}
10
In this case the actual variable x
is not changed, because we pass argument by value, hence a copy of x is passed, which is changed, and that copied value is destroyed as the function ends(goes out of scope). So the variable x inside main() still has a value 10.
But we can change this program to modify the original x, by making the function calc() return a value, and storing that value in x.
int calc(int x);
int main()
{
int x = 10;
x = calc(x);
printf("%d", x);
}
int calc(int x)
{
x = x + 10 ;
return x;
}
20
In this we pass the address of the variable as arguments. In this case the formal parameter can be taken as a reference or a pointer, in both the case they will change the values of the original variable.
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;
}
20
NOTE: If you do not have a prior knowledge of pointers, do study pointers first.