Chapter 5
Chapter 5
FUNCTION
Function
{
int r;
r=a+b;
return r;
}
int main () // main function
{
int z;
z = addition (5, 3);
cout << "The result is: " << z;
return 0;
}
A C++ program always begins its execution by the main
function. So this program starts its execution from there.
We can see how the main function begins by declaring the
variable z of type int.
Right after that, we see a call to a function called
addition.
similarity between the structure of the call to the function
and the declaration of the function itself
Within the main function we called to addition passing two values:
5 and 3, that correspond to the int a and int b parameters declared for
function addition.
At the point at which the function is called from within main (), the
control is lost by main and passed to function addition.
Function addition declares another local variable (int r), and by
means of the expression r=a+b, it assigns to r the result of a plus b.
Because the actual parameters passed for a and b are 5 and 3
respectively, the result is 8.
return r; finalizes function addition,
the call to a function (addition (5, 3)) is literally replaced
by the value it returns (8).
cout << "The result is:" << z;
That, as you may already expect, produces the printing of
the result on the screen.
Declaring functions
This declaration is shorter than the entire definition, but significant
enough for the compiler to determine its return type and the types
of its parameters.
type name ( argument_type1, argument_type2, ...);
It is identical to a function definition, except that it does not
include the body of the function itself (i.e., the function statements
that in normal definitions are enclosed in braces ({}) and instead of
that we end the prototype declaration with a mandatory semicolon
(;).
For example, we can declare a function called protofunction with
two int parameters with any of the following declarations:
int protofunction (int first, int second); or
int protofunction (int, int);
//declaring functions prototypes
#include <iostream.h>
void odd (int a);
void even (int a);
int main ()
{
int i;
cout << "Type any number to check and 0 to exit: ";
cin >> i;
while(i)
{
odd (i);
cout << "Type any number to check and 0 to exit: ";
cin >> i;
}
cout<<"Thank you for using this application!\n";
return 0;
}
void odd (int a)
{