Functions are pieces of code, that can be executed by calling from another function. You know that a common C++ application, must have one function, that functions is int main().
So there is a statement of a function
return_type function_name(parameter1, parameter2,...)
- return_type, is the type that the function returns as a result (eg. int, float, string,...). It can be void, if the function doesn't return anything.
- function_name, is the identifier of the function, we can call the function using that identifier
- parameters, values that we give to the function to make some operations with them
- statements, the code in the function, it is surrounded by braces
- using namespace std;
- int sum(int a, int b)
- return a+b;
- int main()
- int x=5;
- int y=6;
- int z=sum(x, y);
- cout << z << endl;
The function expects two arguments, the first will be the value of x, the second will be the value of y. And it will return their sum.
So, we initialize two variables, x and y. And the variable z will get the value of the sum of x and y. That operation is performed by the function.