Functions

A Function is a named unit of a group of program statements. This unit can be invoked from other parts of the program. With the help of a function the program becomes easy to handle and ambiguity is avoided when dealing with a small part of the program. The size of the program also reduced by the use of functions in a prgram.

Functions are pieces of codes that do exactly what their names indicates - performs a task or function in your program. Functions are good because they let you write a code that is modular. Modular code is easy to debug and easy to maintain. In order to use a function, it has to be first declared and then defined.

Delcaring a Function in C++

A function declaration tells the compiler the name of the function and the number, the type and the order of parameters to the function. A function can be declared either in the same source code file in which it is used or in a seperate file and included in the source code file using the #include directive. In C++ a function declaration is also called a function prototype.

A function can thus be declared as:

type name ( argument-type1, argument-type2,....);

where,

type is the data type returned by the function

name is the name by which the function is called.

argument is the value or address passed to a procedure or function at the time of call. More than one argument can be specified. Each argument consists of a data type followed by a particular name, or in a variable declaration.

For example:

float area(float a, float b)

int mul(int, int); // variable names are optional

Function Prototype

Function prototype or declaration is a very useful feature of a C++ program. Prototyping consists of making a shorter declaration of the complete definition of a function initially. Through this declartion the compiler knows the type of arguments that will be passed to the function and return data type needed.

For example:

#include<iostream.h>

void odd(int a); //prototype of function odd

void even(int a); // prototype of function even

int main()

{

int i;

do {

cout <<"Type a numner:(0 to exit)";

cin>>i;

odd(i);

}while (i!=0);

return 0;

}

void odd(int a)

{

if ((a%2)!=0)cout<<"Number is odd.\n";

else even(a); // call for function even

}

void even(int a)

{

if ((a%2)==0)cout<<"Number is even.\n";

else odd(a); // call for function odd

}

In this example, two functions - odd and even have been declared or prototyped in the beginning of the program. they are called / used later within the function main.

HOME LEARN C++ PREVIOUS NEXT