0% found this document useful (0 votes)
3 views

C++ Modularisation

C++ functions are essential for breaking down larger programs into manageable modules, allowing for easier design, implementation, and maintenance. Functions encapsulate specific tasks, promote code reusability, and enhance program readability by hiding implementation details. There are built-in functions provided by C++ and user-defined functions that programmers can create to meet specific needs.

Uploaded by

gamunorwataku
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C++ Modularisation

C++ functions are essential for breaking down larger programs into manageable modules, allowing for easier design, implementation, and maintenance. Functions encapsulate specific tasks, promote code reusability, and enhance program readability by hiding implementation details. There are built-in functions provided by C++ and user-defined functions that programmers can create to meet specific needs.

Uploaded by

gamunorwataku
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

FUNCTIONS IN C++

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

o A descriptive function name, e.g.


[email protected], [email protected] 1|Page
FUNCTIONS IN C++
 computeTaxes() to compute the taxes for an employee
 isPrime() to check whether or not a number is a prime number
o A returning value
 The computeTaxes() function may return with a double number
representing the amount of taxes
 The isPrime() function may return with a Boolean value (true or false)
 Every C++ program must have a function called main
 Program execution always begins with function main
 Any other functions are subprograms and must be called
 Function call analogy:
o Boss asks worker to complete task
o Worker gets information, does task, returns result
o Information hiding: boss does not know details

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

[email protected], [email protected] 2|Page


FUNCTIONS IN C++
 Software reusability
o Use existing functions as building blocks for new programs
o Abstraction - hide internal details (library functions)
 Avoid code repetition
 To help make the program more understandable
 To modularize the tasks of the program
o building blocks of the program
 Write a module once
o those lines of source code are called multiple times in the program
 While working on one function, you can focus on just that part of the program
o construct it,
o debug it,
o perfect it.

 Different people can work on different functions simultaneously.


 If a function is needed in more than one place in a program, or in different programs, you
can write it once and use it many times

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

[email protected], [email protected] 3|Page


FUNCTIONS IN C++
When we have a function in our program, then depending on the requirement we need to call or
invoke this function. Only when the function is called or invoked, the function will execute its
set of statements to provide the desired results.

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.

functionName (argumentList) e.g. sqrt(x);

 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:

return statement (with or without a return value),

or,

closing brace of function body.

 Then control goes back to where the function was called.


 When another function is called logical control is passed to first statement in that
function’s body and the program proceeds through the sequence of statements within the
function
 When the closing brace or the return statement of the function is executed control returns
to where function was called.

#include <iostream>

using namespace std;

int calculateCube ( int x )

int result;

[email protected], [email protected] 4|Page


FUNCTIONS IN C++
result = x * x * x;

return result;

int main ( )

int yourNumber, myNumber ;

yourNumber = 14 ;

myNumber = 9;

cout<< “My Number = “ << myNumber

cout<< “its cube is “ << calculateCube (myNumber) << endl ;

cout<< “Your Number = “ << yourNumber ;

cout<< “its cube is “ << calculateCube (yourNumber) << endl ;

return 0;

In C++, we have two types of functions as shown below.

[email protected], [email protected] 5|Page


FUNCTIONS IN C++

C++ Built-in/Standard/Pre-defined Functions

 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.

 Make sure to use the required #include file


 The syntax of a predefined function is:

functionName(Parameter1, Parameter2, ...);

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.

[email protected], [email protected] 6|Page


FUNCTIONS IN C++
 Be careful about the actual number of parameters a function has, and the types of values
the parameters can take on, and restrictions or assumptions for the parameter values and
the returned value.
 A function is used (called) by supplying the function name together with values for the
parameters of the function enclosed by parentheses and separated from each other by
commas. The parentheses cannot be omitted even if the function has no parameters. For
example the function that generates a random integer: rand( ).
 Each of the predefined function returns a single value of a specific type when it is called.
 To use these functions, the appropriate header files must be included using preprocessor
directives. For example the above rand function requires the directive: #include
<cstdlib>.
 Another example is the function sqrt(x), which has a parameter, x, of type double. It
returns the square root of x, also of type double. That function is defined in the header
file cmath and so one has to use the preprocessor directive: #include <cmath>. The actual
argument used must not be negative, and only the positive square root is returned.

 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>

[email protected], [email protected] 7|Page


FUNCTIONS IN C++
Example of Using Standard C++ Math Functions

#include <iostream.h>

#include <math.h>

void main()

double x;

cout<< "Please enter a real number: ";

cin>> x;

cout<< "The ceil(" << x << ") = " << ceil(x) << endl;

cout<< "The floor(" << x << ") = " << floor(x) << endl;

Example of Using Standard C++ Character Functions

#include <iostream>

#include <ctype>

using namespace std;

int main()

char ch;

cout<< "Enter a character: ";

cin>> ch;

cout<< "The toupper(" << ch << ") = " << (char) toupper(ch) << endl;

cout<< "The tolower(" << ch << ") = " << (char) tolower(ch) << endl;

[email protected], [email protected] 8|Page


FUNCTIONS IN C++
if (isdigit(ch))

cout << "'" << ch <<"' is a digit!\n";

else

cout << "'" << ch <<"' is NOT a digit!\n";

return 0;

[email protected], [email protected] 9|Page


FUNCTIONS IN C++

User-Defined C++ Functions

 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

Syntactic Structure of a C++ user defined Function

 A C++ function consists of two parts


o The function header - A function header tells the compiler about the return type of
function, function name, and the number of parameters used by the function and

[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 { }

The general form of a function definition in C++ is as follows:

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.

 int square( int ); //Function takes an int and returns an int


 int Cube( int ); // prototype
• A function prototype contains
– Function name
– Parameters (number and data type)
– Return type (void if returns nothing)
– Only needed if function definition after function call
• Prototype must match function definition
– Function prototype
double maximum( double, double, double );
– Definition
double maximum( double x, double y, double z )
{

}

If the Function does not RETURN result, it is called void Function


#include<iostream.h>
void add2Nums(int,int);
main()
{ int a, b;
cout<<“enter tow Number:”;
[email protected], [email protected] 13 | P a g e
FUNCTIONS IN C++
cin>>a >> b;
add2Nums(a, b)
return 0;
}
void add2Nums(int x, int y)
{
cout<< x<< “+” << y << “=“ << x+y;
}

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, ...).

– Declarations and statements: function body (block)


• Variables can be declared inside blocks (can be nested)
• Functions cannot be defined inside other functions
– Returning control
• If nothing returned
– return;
– or, until reaches right brace
• If something returned
– return expression;

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.

Function return Statement

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
}

Return required in non-void functions


If a function returns a value, it must have a return statement that specifies the value to return. It's
possible to have more than one return, but the (human) complexity of a function generally
increases with more return statements. It's generally considered better style to have one return at
the end, unless that increases the complexity.

The max function below requires one or more return statements because it returns an int value.

int max(int a, int b)


{
if (a > b)
return a;
else
return b;
}

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.

Actual Parameters or Arguments


When a function is called, the values (expressions) that are passed in the call are called the
arguments or actual parameters (both terms mean the same thing). At the time of the call each
actual parameter is assigned to the corresponding formal parameter in the function definition.
Parameters written in function call is called “actual parameters/arguments”. One can use
numbers, expressions, or even function calls as actual parameters or arguments.

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.

Actual vs. Formal Parameters


The Actual parameters are the values The Formal Parameters are the variables
that are passed to the function when it defined by the function that receives values
is invoked. when the function is called.

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

In actual parameters, there is no


In formal parameters, the data types of the
mentioning of data types. Only the
receiving values should be included.
value is mentioned.

Function Reference Parameters

Reference parameters are useful in two cases:


 Change values. Use a reference parameter when you need to change the value of an
actual parameter variable in the call. When a function computes only one value it is
considered a better style to return the value with the return statement. However, if a
function produces more than one value, it is common to use reference parameters to
return values, or a combination of the return value and reference parameters.
 Efficiency. To pass large structures more efficiently. This is especially common for
passing structs or class objects. If no changes are made to the parameter, it is should be
declared const.

[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

Call by Reference/ Call by Address/ Reference Parameters


 Reference parameters are implemented by passing the memory address of the actual
parameter to the formal parameter. Reference parameters are used to pass values back
from a function. This is necessary to return more than one value.
 A reference parameter is indicated by following the formal parameter name in the
function prototype/header by an ampersand (&). The compiler will then pass the memory
address of the actual parameter, not the value.
– Passes the address of the argument
– Changes in function affect original
– Only used with trusted functions
 We introduce reference-parameter, to perform call by reference. The caller gives the
called function the ability to directly access the caller’s value, and to modify it.
 A reference parameter is an alias for its corresponding argument, it is stated in c++ by
“flow the parameter’s type” in the function prototype by an ampersand (&) also in the
function definition-header.
o Changes in function affect original parameters
o Only used with trusted functions

[email protected], [email protected] 19 | P a g e
FUNCTIONS IN C++
void functionName (type &); // prototype
void main()
{
-----
------
}
void functionName(type &parameterName)

#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;
}

Call by value Call by reference

A copy of value is passed to the function An address of value is passed to the


function

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;
}

void add(double a, double b)


{
double sum;
sum = a + b;
cout << "The sum of the 2 double values is "<<sum;
}

int main()
{
add(10, 2);
add(5.3, 6.2);
return 0;
}

 Parameters should have a different number


add(int a, int b)
add(int a, int b, int c)
Example:
#include <iostream>
using namespace std;

void add(int a, int b)


{
cout << "sum = " << a + b)
}

void add(int a, int b, int c)


{
cout << endl << "sum = " << a + b + c);
}

int main()
{

[email protected], [email protected] 22 | P a g e
FUNCTIONS IN C++
add(10, 2);
add(5, 6, 4);

return 0;
}

 Parameters should have a different sequence of parameters.


add(int a, double b)
add(double a, int b)
Example:
#include<iostream>
using namespace std;

void add(int a, double b)


{
double sum;
sum = a + b;
cout<<"The sum of the 2 numbers is "<<sum;
}

void add(double a, int b)


{
cout<<endl<<"sum = "<<(a+b);
}

// 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

Local vs. Global 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

You might also like