You are on page 1of 8

C++ Functions

We know that function play an important role in C program development. Dividing a


program into functions is one of the major principles of top-down, structure
programming.

Another advantage of using functions is that it is possible to reduce the size of a program
by calling and using them at different places in the program

Example

void show ( ); /* Function declaration */

main ( )

………..

Show ( ); /* Function call */

………..

void show ( ) /* Function definition */

……….. /* Function body */

………..

………..

}
THE MAIN FUNCTION

C does not specify any return type for the main() function which is the starting point for
the execution of a program. The definition of main() would look like this:

main ( )
{
// main program statements
}

This is perfectly valid because the main () in C does not return any value.

In C++, the main() returns a value of type int to the operating system. C++, therefore,
explicitly defines main() as matching one of the following prototypes:

int main();
int main(int args, char * argv []);

C++ Functions

The functions that have a return value should use the return statement for termination.
The main() function in C++ is, therefore , defines as follows:

int main()
{
………..
………..
return 0;
}

Since the return type of functions is int by default he keywords int in the main()
header is optional. Most C++ compilers will generate an error or warning if there is
no return statement. Turbo C++ issues the warning
Function should return a value

And then proceeds to compile the program. It is good programming practice to


actually return a value from main().

FUNCTION PROTOTYPING

Function prototyping is one of the major improvements added to C++ functions. The
prototype describes the function interface to the compiler by giving details such as
the number and type of arguments and the type of returns values.

Function prototype is a declaration statement is the calling program and is of the


following form:

type function-name (argument - list)

Examples:

float volume (int x, float y, float z);

C++ FUNCTION OVERLOADING

Overloading refers to the use of same thing for different purpose. C++ also permits
overloading of functions. This means that we can use the same function name to crate
functions that perform a variety of different tasks. This is known as function
polymorphism in OOP

Using the concept of function overloading; we can design a family of functions with
one function name but with different arguments lists. The function would perform
different operations depending on the argument list in the function call.

For examples, an overloaded add() function handles different types of data as shown
below:

// declarations
int add (int a, int b); // prototype 1
int add (int a, int b, int c) // prototype 2
double add (int p, double q) // prototype 3

//function calls
cout << add(5, 10) // uses prototype 1
cout << add(15, 10.0) // uses prototype 3

A function call first matches the prototype having the same number and type of
arguments and then calls the appropriate function for execution.

// function volume() is overloaded three times Output


#include 1000
using namespace std; 157.26
// declarations (prototypes) 112500
int volume(int);
double volume (double, int);
long volume (long, int, int);
int main()
{
cout << volume(10) << “\n”;
cout << volume(2.5, 8) << “\n”;
cout << volume(100L, 75, 15) << “\n”;
return 0;
}
// function definitions
int volume(int s) // cube
{
return(s*s*s);
}
double volune(double r, int h) // cylinder
{
return(3.14519*r*r*h);
}
Long vlume(long l, int b, int h) // rectangular box
{
return(l*b*h);
}

Function Declaration

A function declaration is made by declaring the return type of the function, name of the
function and the data types of the parameters of the function. A function declaration is
same as the declaration of the variable. The function declaration is always terminated by
the semicolon. A call to the function cannot be made unless it is declared. The general
form of the declaration is:-

return_type function_name(parameter list);

For example function declaration can be

int factorial(int n1,float j1);

The variables name need not be same as the variables of parameter list of the function.
Another method can be

int factorial(int , float);

The variables in the function declaration can be optional but data types are necessary.
C++ Function Definitions
Function definitions differ from function declarations in that they supply function bodies
— the code that makes up the function. The form of a function definition is:
decl-specifiers declarator [cv-qualifers] [exception-specification]
{
// function body
}

The parts of the definition are:

Declaration specifiers, as described in Function Declarations.

The declarator. See below.

An optional const or volatile qualifier. In this context, const may only be used for class
members, and is used to indicate that the function will not modify data members of the
class.

Exception specification describing what exceptions the function may throw. See
Exception Specifications.

Function-body, consisting of statements enclosed in curly braces {}.

The form of the declarator is:

Optional pointer or reference operators modifying the return type

An optional Microsoft specific modifier. See Microsoft Specific Modifiers.

The name of the function. If the function is a member of a class or struct, the name may
be qualified using the scope resolution operator.

The argument declaration list enclosed in parentheses ().

For constructors, an optional constructor initializer (see below).

See the comments in Function Declarations on functions returning function pointers for
information on the form of the declarator in such cases.

The formal arguments declared in the argument declaration list are in the scope of the
function body.

The following figure shows the parts of a function definition. The shaded area is the
function body.
Parts of a Function Definition

The constructor initializer element of the syntax is used only in constructors. Its purpose
is to allow initialization of base classes and contained objects. (For more information
about use of the constructor initializer, see Initializing Bases and Members.)

8. Recursion
8.1 The Basic Idea

We have already seen how, in a well designed C++ program, many function definitions
include calls to other functions (for example, in the last lecture the definition of
"assign_list(...)" included a call to "assign_new_node(...)"). A function is recursive (or
has a recursive definition) if the definition includes a call to itself.

Recursion is a familiar idea in mathematics and logic. For example, the natural numbers
themselves are usually defined recursively. Very roughly speaking, the definition is:
0 is a natural number.

if n is a natural number then s(n) (i.e. n+1) is a natural number, where s is the "successor
function".

In this context, the notion of recursion is clearly related to the notion of mathematical
induction. Notice also that the above definition includes a non-recursive part or base case
(the statement that 0 is a natural number).

Another familiar mathematical example of a recursive function is the factorial function


"!". Its definition is:
0! = 1

for all n > 0, n! = nx(n-1)!

Thus, by repeatedly using the definition, we can work out that


6! = 6x5! = 6x5x4! = 6x5x4x3! = 6x5x4x3x2! = 6x5x4x3x2x1! = 6x5x4x3x2x1x1 = 720

Again, notice that the definition of "!" includes both a base case (the definition of 0!) and
a recursive part.
(BACK TO COURSE CONTENTS)
8.2 A Simple Example

The following program includes a call to the recursively defined function


"print_backwards()", which inputs a series of characters from the keyboard, terminated
with a full-stop character, and then prints them backwards on the screen.
#include<iostream>
using namespace std;

void print_backwards();

int main()
{
print_backwards();
cout << "\n";

return 0;
}

void print_backwards()
{
char character;

cout << "Enter a character ('.' to end program): ";


cin >> character;
if (character != '.')
{
print_backwards();
cout << character;
}
}

You might also like