C++ Modularisation
C++ Modularisation
C++ FUNCTIONS
Computer programs that solve real-world problems are usually much larger than the
simple programs discussed so far. To design, implement and maintain larger programs it
is necessary to break them down into smaller, more manageable pieces or modules.
Dividing the problem into parts and building the solution from simpler parts is a key
concept in problem solving and programming.
In C++ we can subdivide the functional features of a program into blocks of code known
as functions. In effect these are subprograms that can be used to avoid the repetition of
similar code and allow complicated tasks to be broken down into parts, making the
program modular.
A natural way to solve large problems is to break them down into a series of sub
problems, which can be solved more or less independently and then combined to arrive at
a complete solution. In programming, this methodology reflects itself in the use
of subprograms, and in C++ all sub-programs are called functions.
You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division usually is such that each
function performs a specific task.
A function is a group of statements that together perform a task and can be processed
independently. Every C++ program has at least one function, which is main(), and
programmers can define additional functions.
Functions are useful for encapsulating common operations in a single reusable block,
ideally with a name that clearly describes what the function does.
When the program passes control to a function the function performs that task and returns
control to the instruction following the calling instruction. The most important reason to
use the function is make program handling easier as only a small part of the program is
dealt with at a time.
A function is a “black box” that we’ve locked part of our program into. The idea behind a
function is that it compartmentalizes/modularizes part of the program, and in particular,
that the code within the function has some useful properties.
Functions are used to provide modularity to a program. Creating an application using
function makes it easier to understand, edit, check errors etc.
A function is known with various names like a method or a sub-routine or a procedure etc.
The Top-down design approach is based on dividing the main problem into smaller tasks
which may be divided into simpler tasks, then implementing each simple task by a
subprogram or a function
A C++ function or a subprogram is simply a chunk of C++ code that has
Benefits of functions
1. Functions allow the divide and conquer strategy to be used for the development of
programs. When developing even a moderately sized program, it is very difficult if not
impossible, to write the entire program as a single large main function. Such programs are
very difficult to test, debug and maintain. The task to be performed is normally divided
into several independent subtasks, thereby reducing the overall complexity; a separate
function is written for each subtask. In fact, we can further divide each subtask into smaller
subtasks, further reducing the complexity.
2. Functions help avoid duplication of effort and code in programs. During the development
of a program, the same or similar activity may be required to be performed more than once.
The use of functions in such situations avoids duplication of effort and code in programs.
This reduces the size of the source program as well as the executable program. It also
reduces the time required to write, test, debug and maintain such programs, thus reducing
program development and maintenance cost.
3. Functions enable us to hide the implementation details of a program, e. g., we have used
library functions such as sqrt(), log(), sin(), etc. without ever knowing how they are
implemented. However, although we need to know the implementation details for user-
defined functions, once a function is developed and tested, we can continue to use it without
going into its implementation details. Another consequence of hiding implementation
details is improvement in the readability of a program. Proper use of functions leads to
programs that are easier to read and understand.
4. The divide and conquer approach also allows the parts of a program to be developed, tested
and debugged independently and possibly concurrently by members of a programming
team. The involvement of several programmers, which is the norm in the development of
a software project, reduces the overall development time.
o The functions developed for one program can be used, if required, in another with
little or no modification. This further reduces program development time and cost.
o Manageable program development
Calling/Invoking a function
While creating a C++ function, you give a definition of what the function has to do. To
use a function, you will have to call or invoke that function. A function must be called by
its name followed by argument list enclosed in semicolon.
When a program calls a function, program control is transferred to the called function. A
called function performs defined task and when it’s return statement is executed or when
its function-ending closing brace is reached, it returns program control back to the main
program.
To call a function, you simply need to pass the required parameters along with function
name, and if function returns a value, then you can store returned value.
One function calls another by using the name of the called function next to ( ) enclosing
an argument list.
A function call temporarily transfers control from the calling function to the called
function.
A void function is called by using the function name and the argument list as a
statement in the program.
For value returning functions; its either in an assignment, mathematical expression or
cout statement
The function can be called from anywhere in the program. It can be called from the main
function or from any other function if the program is using more than one function. The function
that calls another function is called the “Calling function”.
In the above example of swapping numbers, the swap function is called in the main function.
Hence the main function becomes the calling function.
The argument list is a way for functions to communicate with each other by passing
information.
The argument list can contain 0, 1, or more arguments, separated by commas, depending
on the function.
Then the flow of control passes to the first statement in the function’s body. The called
function’s body statements are executed until one of these occurs:
or,
#include <iostream>
int result;
return result;
int main ( )
yourNumber = 14 ;
myNumber = 9;
return 0;
Built-in functions are also called library functions. These are the functions that are
provided by C++ and we need not write them ourselves. We can directly use these
functions in our code.
The C++ standard library provides numerous built-in functions that your program can call.
For example, function strcat() to concatenate two strings, function memcpy() to copy one
memory location to another location and many more functions.
where functionName is the name of the function, and Parameter1 is the first parameter of
the function, Parameter2 is its second parameter, etc.
A predefined function may have zero, one or more parameters.
Another useful predefined function is pow(a, b), which computes a raised to the b power.
Note that an error will occur if a=0 and b is negative, or if a is negative and b is not an
integer.
The actual arguments supplied to the function when it is called, can be literal constants,
variables or expressions, provided their types agree with those assumed of the function
parameters, and the variable or expression has a value.
These standard functions are groups in different libraries which can be included in the
C++ program, e.g.
o Math functions are declared in <cmath> library
o Character-manipulation functions are declared in <ctype> library
o C++ is shipped with more than 100 standard libraries, some of them are very
popular such as <iostream> and <stdlib>, others are very specific to certain
hardware platform, e.g. <limits> and <largeInt>
#include <iostream.h>
#include <math.h>
void main()
double x;
cin>> x;
cout<< "The ceil(" << x << ") = " << ceil(x) << endl;
cout<< "The floor(" << x << ") = " << floor(x) << endl;
#include <iostream>
#include <ctype>
int main()
char ch;
cin>> ch;
cout<< "The toupper(" << ch << ") = " << (char) toupper(ch) << endl;
cout<< "The tolower(" << ch << ") = " << (char) tolower(ch) << endl;
else
return 0;
C++ language allows additional functions besides the built-in functions called the user-
defined function. It allows programmers to define their own functions. The programmer
must code the logic of this type. In order to do so, a declaration is needed.
C++ also allows its users to define their own functions. These are the user-defined
functions. We can define the functions anywhere in the program and then call these
functions from any part of the code. Just like variables, it should be declared before using,
functions also need to be declared before they are called.
Although C++ is shipped with a lot of standard functions, these functions are not enough
for all users, therefore, C++ provides its users with a way to define their own functions
(or user-defined function)
For example, the <cmath> library does not include a standard function that allows users
to round a real number to the ith digits, therefore, we must declare and implement this
function ourselves
[email protected], [email protected] 10 | P a g e
FUNCTIONS IN C++
its data types. Including the names of the parameters in the function, the
declaration is optional.
o The function body
The function header has the following syntax
o <return value><name> (<parameter list>)
The function body is simply a C++ code enclosed between { }
returnType functionName(parameterList )
{
local declarations
Executable statements
<return statement>
}
If the function returns a value then the type of that value must be specified in function-
type. For the moment this could be int, float or char. If the function does not return a
value then the function-type must be void.
The function-name follows the same rules of composition as identifiers.
The parameter-list lists the formal parameters of the function together with their types.
The local-definitions are definitions of variables that are used in the function-
implementation. These variables have no meaning outside the function.
The function-implementation consists of C++ executable statements that implement the
effect of the function
Naming a function
For a function to work well as a conceptual unit it has to have a name that is clear to the human
reader.
Choose a name that has a clear meaning. Eg, "f" is not a good name.
[email protected], [email protected] 11 | P a g e
FUNCTIONS IN C++
Void functions are more readable if a verb name is used that describes what it does. Eg,
"printAverage" would be a good name for a void function that prints the average of some
numbers. "Average" would not be a good name for it.
Value-returning functions
o A verb is a good choice for a value returning function that performs an operation
that would naturally be understood to produce a value, eg, "add(x, y)". A noun
which describes the the result can be used. For example, "remainder(a, b)" would
be a good choice for a function that computes the remainder after division (ie,
what the "%" operator does). The noun is a good choice if you're tempted to add a
word like "compute" or "calculate" in front (eg, "computeRemainder(a, b)"). The
"compute" or "calculate" is simple often omitted if the meaning is clear.
o Getter and setter functions. Prefix functions which get a value from an object or
data structure with "get" (eg, getTime()). Similarly use "set" for functions that set
values (eg, setTime()).
o boolean functions should usually start with "is" or another word that suggests a
yes/no answer. Eg, "isOdd(n)" is a good name for a function that returns true if its
parameter is odd, and it's better than simply "odd()".
Case. There are several conventions, but whichever one you choose, be consistent to
make programs readable. The most common convention is to start names with lowercase
and capitalize the first letter of each additional word in the name. Some programmers
start functions with uppercase characters, but this is less common.
Each function should do only one thing. This should be done so that the conceptual
unit can be understood easily. Sometimes it will be convenient to do two things in a
function because you're working on the same data. Try to resist this temptation. Make
two functions if you reasonably can.
Prototypes/Function Declaration
Every function (except main) should be declared near the beginning of a program with a
prototype which gives the return type (or void), name, and the parameter names and types.
A function prototype is a declaration of a function that tells the program about the type of value
returned by the function, name of function, number and type of arguments. Parameter names are
optional in prototypes, but they are very useful to readers of your program.
A function declaration tells the compiler about the return type of function, the number of
parameters used by the function and its data types. Including the names of the parameters in the
function, the declaration is optional. The function declaration is also called as a function
prototype.
void printChars(char c, int count);
OR
void printChars(char, int);
[email protected], [email protected] 12 | P a g e
FUNCTIONS IN C++
Note that prototypes always end with a semicolon. If you are developing a program with many
modules, it’s common to put the prototypes into an include file. Assuming you are using
prototypes, the order of the later function definitions doesn't matter. Prototypes are needed by the
compiler to know how many and type of the parameters, and the return value type.
A prototype looks like a heading but must end with a semicolon; and its parameter list just needs
to contain the type of each parameter. It Tells compiler argument type and return type of function
e.g.
Function Definition
A function definition contains everything that a function declaration contains and additionally it
also contains the body of the function enclosed in braces ({}).
In addition, it should also have named parameters. When the function is called, control of the
program passes to the function definition so that the function code can be executed. When
execution of the function is finished, the control passes back to the point where the function was
called.
The first line of a function definition (called the function header) is the prototype, except that it is
followed by the function body in braces. Neither the header nor the body is followed by a
semicolon.
void displayChars(char c, int count)
{
for (int i=0; i<count; i++)
cout<< c;
}
A C++ function definition consists of a function header and a function body. Here are all the
parts of a function:
Return Type: A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
[email protected], [email protected] 14 | P a g e
FUNCTIONS IN C++
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
Function Body: The function body contains a collection of statements that define what
the function does.
void functions
If a function doesn't return a value (perhaps it changes a reference parameter, changes a global,
or produces a side-effect like I/O), it must be declared as void type. In some programming
languages (Visual Basic, Pascal, Fortran, ...), void functions are called by a different name
(subroutine, procedure, ...).
Return statement
The return statement stops execution and returns control to the calling function. A void function
doesn't need a return statement -- when the end is reached, it automatically returns. However, a
void function may optionally have one or more return statements.
return statement
The return statement stops execution and returns control to the calling function. When a return
statement is executed, the function is terminated immediately at that point, regardless of whether
it's in the middle of a loop, etc.
[email protected], [email protected] 15 | P a g e
FUNCTIONS IN C++
Return optional in void functions
A void function doesn't have to have a return statement -- when the end is reached, it
automatically returns. However, a void function may optionally contain one or more return
statements.
void printChars(char c, int count)
{
for (int i=0; i<count; i++)
cout<< c;
return; // Optional because it's a void function
}
The max function below requires one or more return statements because it returns an int value.
Here is a version of the max function that uses only one return statement by saving the result in a
local variable. Some authors insist on only one return statement at the end of a function.
Readable code is much more important than following such a fixed rule. The use of a single
return probably improves the clarity of the max function slightly.
int max(int a, int b)
{
int maxval;
[email protected], [email protected] 16 | P a g e
FUNCTIONS IN C++
if (a > b)
maxval = a;
else
maxval = b;
return maxval;
}
Function Parameters
Formal Parameters
Formal parameters are written in the function prototype and function header of the definition.
Formal parameters are local variables which are assigned values from the arguments when the
function is called. They are place holders for the actual parameter values in the calling function.
Parameter written in function definition is called “formal parameters”. Formal parameters are
always variables, while actual parameters do not have to be variables.
For value parameters (the default), the value of the actual parameter is assigned to the formal
parameter variable. For reference parameters, the memory address of the actual parameter is
assigned to the formal parameter.
Related Function
The actual parameters are passed by The formal parameters are in the called
the calling function. function.
[email protected], [email protected] 17 | P a g e
FUNCTIONS IN C++
Data Types
[email protected], [email protected] 18 | P a g e
FUNCTIONS IN C++
Function Call Methods
Call by value/ Value Parameters
A copy of the actual parameter value into the formal parameter. Changes to the formal
parameter, which is a local variable, do not get passed back to the calling program.
By default, argument values are simply copied to the formal parameter variables at the
time of the call. This type of parameter passing is called pass-by-value. It is the only kind
of parameter passing in Java and C. C++ also has pass-by-reference (see below).
– Copy of argument passed to function
– Changes in function do not effect original
– Use when function does not need to modify argument
• Avoids accidental changes
Up to this point all the calls we have seen are call-by-value, a copy of the value (known)
is passed from the caller-function to the called-function
Any change to the copy does not affect the original value in the caller function
Changes in function do not effect original
[email protected], [email protected] 19 | P a g e
FUNCTIONS IN C++
void functionName (type &); // prototype
void main()
{
-----
------
}
void functionName(type ¶meterName)
#include<iostream>
using namespace std;
int squareVal(int); //prototype call by value function
void squareRef(int &); // prototype call by –reference function
int main()
{
int x = 2, z = 4;
cout<< “x = ” << x << “before calling squareVal”;
cout<< ‘\n’ << squareVal(x) << ‘\n’; // call by value
cout<< “x = “ << x << “After returning”;
cout<< “z = “ << z << “before calling squareRef”;
squareRef(z); // call by reference
cout<< “z = “ << z<< “After returning squareRef”
return 0;
}
int squareVal(int a)
{
return a*= a; // caller’s argument not modified
}
[email protected], [email protected] 20 | P a g e
FUNCTIONS IN C++
void squareRef(int &cRef)
{
cRef *= cRef; // caller’s argument modified
cout<<cRef;
}
Changes made inside the function is not Changes made inside the function is
reflected on other functions reflected
outside the function also
Actual and formal arguments will be created Actual and formal arguments will be created
in different memory location in same memory location.
Function overloading
C++ lets you specify more than one function of the same name in the same scope. These
functions are called overloaded functions, or overloads. Overloaded functions enable you to
supply different semantics for a function, depending on the types and number of its arguments.
Functions with same name and different parameters.
Function overloading is a feature of object-oriented programming where two or more functions
can have the same name but different parameters. When a function name is overloaded with
different jobs it is called Function Overloading. In Function Overloading “Function” name
should be the same and the arguments should be different. Function overloading can be
considered as an example of a polymorphism feature in C++.
The parameters should follow any one or more than one of the following conditions for
Function overloading:
Parameters should have a different type
add(int a, int b)
add(double a, double b)
[email protected], [email protected] 21 | P a g e
FUNCTIONS IN C++
Example:
#include <iostream>
using namespace std;
void add(int a, int b)
{
int sum;
sum = a + b;
cout << "The sum of the 2 integer numbers is "<<sum;
}
int main()
{
add(10, 2);
add(5.3, 6.2);
return 0;
}
int main()
{
[email protected], [email protected] 22 | P a g e
FUNCTIONS IN C++
add(10, 2);
add(5, 6, 4);
return 0;
}
// Driver code
int main()
{
add(10,2.5);
add(5.5,6);
return 0;
}
The functions should perform similar tasks, for example, a function to square integers and a
function to square floats
int calcSquare( int x)
{
int square;
square = x * x;
[email protected], [email protected] 23 | P a g e
FUNCTIONS IN C++
return square;
}
float calcSquare(float x)
{
float square;
square = x * x;
return square;
}
• At call-time the C++ compiler selects the proper function by examining the number, type
and order of the parameters
[email protected], [email protected] 24 | P a g e
FUNCTIONS IN C++
Understanding Scope/Visibility of Variable
• Every identifier has a scope that is determined by where it is declared. Identifier Scope in
a program is the region(s) of the program within which the identifier can be used. Using a
name outside of its scope is an error. The same name may declared/used in different
scopes.
• Some variables can be accessed throughout an entire program, while others can be
accessed only in a limited part of the program
• The scope of a variable defines where it can be accessed in a program
• To adequately understand scope, you must be able to distinguish between local and
global variables
Global Scope
Variables defined outside and before function main:
Called global variables
Can be accessible and used anywhere in the entire program
If a Global variable defined again as a local variable in a function, then the Local-
definition overrides the Global defining
Global variables are those that are known to all functions in a program
A global object can be used by any function in the file that is defined after the global
object
It is best to avoid programmer-defined global objects
Exceptions tend to be important constants
Global objects with appropriate declarations can even be used in other
program files
Local objects can reuse a global object's name
Unary scope operator :: can provide access to global object even if name reuse has
occurred
Local variables
Local identifiers are identifiers declared within a function block. Local identifiers are not
accessible outside the function or block in which they have been declared.
[email protected], [email protected] 25 | P a g e
FUNCTIONS IN C++
All identifiers that are declared in a function are local to the function. They cannot be
referenced from outside the function (local scope). Their lifetime is the same as the
activation of the function: they are created when the function is called and are destroyed
when the function returns. They have no initial values so will have whatever value
happens to be in memory when they are allocated. Parameters are like local variables
(local scope, function lifetime), but are assigned an initial value from the corresponding
expression in the function call.
• Variables that are declared in a block are local to that block and have the following
characteristics:
– Local variables are created when they are declared within a block
– Local variables are known only to that block
– Local variables cease to exist when their block ends
• Variables declared within a function remain local to that function
• Local variables
– Known only in the function in which they are defined
– All variables declared inside a function are local variables
[email protected], [email protected] 26 | P a g e
FUNCTIONS IN C++
#include<iostream>
using namespace std;
int x,y; //Global Variables
int add2(int, int); //prototype
main()
{
int s;
x = 11;
y = 22;
cout<< “global x=” << x << endl;
cout<< “Global y=” << y << endl;
s = add2(x, y);
cout<< x << “+” << y << “=“ << s;
cout<<endl;
cout<<“\n---end of output---\n”;
return 0;
}
[email protected], [email protected] 27 | P a g e
FUNCTIONS IN C++
int add2(int x1, int y1)
{
int x; //local variable\
x=44;
cout<< “\nLocal x = ” << x << endl;
return x1+y1;
}
[email protected], [email protected] 28 | P a g e