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

Functions Final

The document provides a comprehensive overview of functions in C++, including their definition, types, advantages, and methods of parameter passing. It distinguishes between built-in and user-defined functions, detailing how to declare, define, and call them, as well as the various types of user-defined functions. Additionally, it explains the concepts of actual and formal parameters, and the modes of parameter passing such as by value and by reference.

Uploaded by

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

Functions Final

The document provides a comprehensive overview of functions in C++, including their definition, types, advantages, and methods of parameter passing. It distinguishes between built-in and user-defined functions, detailing how to declare, define, and call them, as well as the various types of user-defined functions. Additionally, it explains the concepts of actual and formal parameters, and the modes of parameter passing such as by value and by reference.

Uploaded by

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

FUNCTIONS

By
Irfan Abdullah
CONTENTS
• Explain the concept and types of functions • Use inline functions
• Explain the advantages of using functions • Pass the arguments
• Explain the signature of functions (Name, • by constants
Arguments, Return type) • by value
• by reference
• Explain Function prototype, Function
definition, Function call • Use default arguments
• Differentiate among local global and static • Use return statement
variable • Know advantage of function overloading
• Differentiate between formal and actual • Understand the use of function
parameters overloading with Number of arguments
• Know the concept of local and global • Data type of arguments
functions
• Return type
Functions
• A function is a group of statements that together perform a task.
• Every C++ programs has at least one function, which is main()
additional functions can be defined in the program. Each
function performs a specific task .
• Functions are one of the main building block of any
programming language. Functions are used to provide
modularity to a program. Creating an application using function
makes it easier to understand, edit, check errors etc. function
makes the work easier by writing the code once and executing it
again and again as many times as required.
Types of Functions
• C++ functions are categorized into the following two types
• Library or built in functions
• User defined functions
Library or Built in Functions
• Library or built in functions are the pre-defined functions in C++ .
• Programmers can use these functions by Invoking calling them
directly, they do not need to write code for them.
• C+ + provides a series of library or pre-defined functions for various
commonly used operations of algebra, geometry, trigonometry,
finance, graphics, clipboards etc. these functions are part of the C++
language and are completely reliable.
• Some examples of commonly used library or built in functions are:
• abs(), div(), getch(), pow(),getchar(), puts(),sqrt(), strcmp(),time()
Library or Built in Functions
// Program to find square root of a number using #include <iostream>
sqrt) built in function
#include<iostream> #include <math.h>
#include<math.h > using namespace std;
using namespace std; int main()
int main() {// Getting a double value
{ double x;
double number, squareroot; cout << "Please enter a real number: ";
cout <<“Enter a number:”; cin >> x;
cin>>number; // Compute the ceiling and the floor of the real number
//sqrt() is a library functions to calculate square root cout << "The ceil(" << x << ") = " << ceil(x) << endl;
squareroot = sqrt(number); cout << "The floor(" << x << ") = " << floor(x) << endl;
cout<<“square root of ”<< number<<“=“<< }
squareroot <<endl;
return 0;
}
User Defined Functions
• C++ allows programmers to define their own functions. The
functions defined by the programmers, according to their needs
are called users defined functions. If any function is not
available as built in function, users can define their own
functions and use them In the same way as built in functions are
used.
• For example, the <math.h> 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
Advantages of User Defined Function
• Single list of instructions within main() • Reducing Complexity of Program:
functions and such programs are known as Complex program can be decomposed into
monolithic program – i.e. program containing small sub-programs or user defined functions.
a large single list of instructions. These types of
programs are very difficult to understand, • Easy to Debug and Maintain : During
debug, test and maintain. So to avoid these debugging it is very easy to locate and isolate
difficulties we use user defined functions. faulty functions. It is also easy to maintain
program that uses user defined functions.
• Advantages of using user defined functions in
C programming are listed below: • Readability of Program : Since while using
user defined function, a complex problem is
• Reduction in Program Size: Since any divided in to different sub-programs with clear
sequence of statements which are repeatedly objective and interface which makes easy to
used in a program can be combined together to understand the logic behind the program.
form a user defined functions. And this
functions can be called as many times as • Code Reusability : Once user defined
required. This avoids writing of same code function is implemented it can be called or
again and again reducing program size. used as many times as required which reduces
code repeatability and increases code
reusability.
Defining a C++ Function
• Generally speaking, we define a C++ • A function must be defined first to use it
function in two steps (preferably but not in the program
mandatory) • A C++ function consists of two parts
1. Declare the function signature in either • The function header, and
a header file (.h file) or before the main • The function body
function of the program
• The general syntax for defining a user
2. Implement the function in either an defined function is
implementation file (.cpp) or after the return-type function-name (parameters)
main function
{
//function-body
}
• The function header has the following
syntax
return-type function-name (parameters)
• The function body is simply a C++ code
enclosed between { }
Function Declarations/Prototype
• A function declaration tells the compiler about a function name
and how to call the function. The actual body of the function can
be defined separately.
• A function declaration has the following parts
return_type function_name( parameter list );
• Example :
int max(int num1, int num2);
• Parameter names are not important in function declaration only
their type is required, so following is also valid declaration.
int max(int, int);
Defining a C++ Function
• The general form of a C++ function definition is as • Following is the source code for a function called max().
follows: This function takes two parameters num1 and num2 and
return_type function_name( parameter list ) return the biggest of both.
{ body of the function }
• A C++ function definition consists of a function header // function returning the max between two numbers
and a function body. Here are all the parts of a function.
• Return Type − A function may return a value. The int max(int num1, int num2) {
return_type is the data type of the value the function // local variable declaration
returns. Some functions perform the desired operations int result;
without returning a value. In this case, the return_type
is the keyword void. if (num1 > num2)
• Function Name − This is the actual name of the result = num1;
function. The function name and the parameter list else
together constitute the function signature. result = num2;
• Parameters − A parameter is like a placeholder. When
a function is invoked, you pass a value to the parameter. return result;
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.
Calling a Function #include <iostream>
using namespace std;
// function declaration
• While creating a C++ function, you give a int max(int num1, int num2);
definition of what the function has to do. To int main () {
use a function, you will have to call or invoke // local variable declaration:
that function. int a = 100;
• When a program calls a function, program int b = 200;
control is transferred to the called function. A int ret;
called function performs defined task and // calling a function to get max value.
when it’s return statement is executed or when ret = max(a, b);
its function-ending closing brace is reached, it cout << "Max value is : " << ret << endl;
returns program control back to the main
program. return 0;
}
• To call a function, you simply need to pass the // function returning the max between two numbers
required parameters along with function
name, and if function returns a value, then you int max(int num1, int num2) {
can store returned value. // local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Types of User-defined Functions in C++
• There can be 4 different types
of user-defined functions,
they are:
1. Function with no arguments
and no return value
2. Function with no arguments
but a return value
3. Function with arguments but
no return value
4. Function with arguments and
a return value
Function with no argument and no return
value
• When a function has no arguments, it does not receive any data from
the calling function. Similarly when it does not return a value, the
calling function does not receive any data from the called function.
• Syntax for function is:

Function declaration : void function();


Function call : function();
Function definition :
void function()
{
statements;
}
Function with no argument and no return
value
#include<iostream> {
using namespace std; if(number % j == 0)
void primeno(); { flag = 1;
int main() break;
{ primeno(); }
return 0; }
} if (flag == 1)
void primeno() { cout << number << " is not a prime
{ number.";
int number, j, flag = 0; }
cout << "Enter any integer and press else
enter to check: "; { cout << number << " is a prime
cin >> number; number.";
for(j = 2; j <= number/2; ++j) }
}
Function with no arguments but a return
value
• There could be occasions where we may need to design functions that may
not take any arguments but returns a value to the calling function. A
example for this is getchar function it has no parameters but it returns an
integer an integer type data that represents a character.
• Syntax for function is:

Function declaration : int function();


Function call : function();
Function definition :
int function()
{
statements;
return x;
}
Function with no arguments but a return
value if (flag == 1)
{
#include <iostream> cout<<number<<"i.e. the number entered by user
using namespace std; which is not a prime number.";
int primeno(); }
int main() else
{ {
int number, j, flag = 0; cout<<number<<"i.e. the number entered by user
which is a prime number.";
/* There is no argument that is passed to }
primeno() function*/ return 0;
number = primeno(); }
for (j = 2; j <= number/2; ++j)
{ // Return type of primeno function is int
if (number%j == 0) int primeno()
{ {
flag = 1; int m;
break; cout<<("Enter any integer value for checking
} purpose: ");
} cin >> m;
return m;
}
Function with arguments but no return value
• When a function has arguments, it receive any data from the
calling function but it returns no values.
• Syntax for function is:

Function declaration : void function ( int );


Function call : function( x );
Function definition:
void function( int x )
{
statements;
}
Function with arguments but no return value
#include <iostream> void prime(int n)
using namespace std; { int i, flag = 0;
void prime(int n); for (i = 2; i <= n/2; ++i)
{
int main() if (n%i == 0)
{ {
int num; flag = 1;
cout << "Enter a positive integer to check: ";
break;
cin >> num;
/* Argument num is passed to the function }
prime()*/ }
prime(num); if (flag == 1)
return 0; { cout << n << " is not a prime number.";
} }
else { cout << n << " is a prime number.";
}
}
Function with arguments and a return value
• In this type of function, the calling function passes the argument to
the called function and called function to send back value to the
calling function. Both functions are depended on each other.
• Syntax for function is:

Function declaration : int function ( int );


Function call : function( x );
Function definition:
int function( int x )
{
statements;
return x;
}
Function with arguments and a return value
#include <iostream> int prime(int n)
using namespace std; {
int prime(int n); int i;
int main() for(i = 2; i <= n/2; ++i)
{ {
int num, flag = 0; if(n % i == 0)
cout << "Enter positive integer to check: "; return 1;
cin >> num; }
// Argument num is passed to check() function
flag = prime(num); return 0;
if(flag == 1) }
cout << num << " is not a prime number.";
else
cout<< num << " is a prime number.";
return 0; }
Actual Parameters versus Formal Parameters
• The variable names assigned to function parameters within the
function are termed “formal” parameters.
• The items passed by code when calling a function, whether
variables or constants, are termed “actual” parameters.
Methods/Modes of Parameter Passing in C++
• In C++, a parameter can be passed by:
• value,
• reference, or
• const-reference
• Each parameter's mode is determined by the way it is specified
in the function's header (the mode is the same for all calls to the
function).
• For example:
void f( int a, int &b, const int &c );
• Parameter a is a value parameter, b is a reference parameter,
and c is a const-reference parameter.
Methods/Modes of Parameter Passing in C++
Pass by Value: #include <iostream>
• When a parameter is passed by using namespace std;
value, a copy of the parameter is void f(int n) {
made or the actual parameter in n++;
the function call is copied into }
the formal parameter in the
function. int main() {
• Therefore, changes made to the int x = 2;
formal parameter by the called f(x);
function have no effect on the cout << x;
corresponding actual parameter. }
• The output of the program is 2
(not 3).
Methods/Modes of Parameter Passing in C++
Pass by Reference // passing parameters by reference
• A reference parameter "refers" to the #include <iostream>
original data in the calling function. thus using namespace std;
any changes made to the parameter are
also made to the original variable. void duplicate (int& a, int& b, int& c)
• There are two ways to make a pass by { a*=2;
reference parameter: b*=2;
1. ARRAYS
c*=2; }
Arrays are always pass by reference in
C++. Any change made to the parameter int main ()
containing the array will change the
value of the original array. {
2. The ampersand used in the function int x=1, y=3, z=7;
prototype.
duplicate (x, y, z);
function ( & parameter_name )
To make a normal parameter into a pass cout << "x=" << x << ", y=" << y << ", z=" << z;
by reference parameter, we use the "& return 0; }
param" notation. The ampersand (&) is
the syntax to tell C that any changes • The output of the program is
made to the parameter also modify the
original variable containing the data. x=2,y=6,z=14
Methods/Modes of Parameter Passing in C++
Pass by Constant Reference // C++ Code using a CONSTANT
reference Parameter
• To protect from accidentally changing #include <iostream>
a reference parameter, when we really using namespace std;
want it not to be changed (we just
want to save time/memory) we can use
the C++ keyword const. void doit(const int &x )
{
• if the function should only access but x = 5; // ILLEGAL
not change a parameter, using const
enforces its not changing }
int main()
• Note: & and const go in the formal {
parameter list they are not in the int z = 27;
function call use the most restrictive
method that works - low coupling doit( z );
cout<<"z is now “<<z <<endl;
return 0;
}
• The output of the program shows an
error.
Default Argument
• A default argument is a value #include<iostream>
provided in a function declaration using namespace std;
that is automatically assigned by int sum(int x, int y, int z=0, int w=0)
the compiler if the caller of the {
function doesn’t provide a value for return (x + y + z + w);
the argument with a default value. }
• If a function with default int main()
arguments is called without {
passing arguments, then the cout << sum(10, 15) << endl;
default parameters are used. cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
• The output of the program is
• 25
• 50
• 80
Return Statement
• Terminates the execution of a int max(int a, int b)
function and returns control to the {
calling function (or to the if (a > b) {
operating system if you transfer return a;
control from the main function). } else {
Execution resumes in the calling return b;
function at the point immediately }
following the call. }
• A function can have any number of
return statements.
• 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.
Local, Global and Static variables in C
Local Variable
• A variable defined inside a function #include <iostream>
(defined inside function body between using namespace std;
braces) is called a local variable or void test();
automatic variable. int main()
• Its scope is only limited to the {
function where it is defined. In simple int var = 5;
terms, local variable exists and can be test();
accessed only inside a function. // illegal: var1 not declared inside
• The life of a local variable ends (It is main()
destroyed) when the function exits. var1 = 9;
}
void test()
{
// local variable to test()
int var1;
var1 = 6;
// illegal: var not declared inside test()
cout << var;
}
Global Variable
• If a variable is defined outside all #include <iostream>
functions, then it is called a global using namespace std;
variable. int c = 12;
• The scope of a global variable is the void test()
whole program. This means, It can be {
used and changed at any part of the ++c;
program after its declaration. cout << c;
• Likewise, its life ends only when the }
program ends. int main()
{
++c;
cout << c <<endl;
test();
return 0;
}
• The output of the program is
• 13
• 14
Static Local Variable
• Keyword static is used for specifying a #include <iostream>
static variable. using namespace std;
• A static local variable exists only void test()
inside a function where it is declared {
(similar to a local variable) but its static int var = 0;
lifetime starts when the function is ++var;
called and ends only when the cout << var << endl;
program ends. }
• The main difference between local int main()
variable and static variable is that, the {
value of static variable persists the end test();
of the program. test();
return 0;
}
• The output of the following program is
• 1
• 2
Inline Function
#include <iostream>
using namespace std;
• C++ inline function is powerful concept that
is commonly used with classes. If a function is inline int Max(int x, int y) {
inline, the compiler places a copy of the code of return (x > y)? x : y;
that function at each point where the function
is called at compile time. }
• Any change to an inline function could require // Main function for the program
all clients of the function to be recompiled
because compiler would need to replace all the int main() {
code once again otherwise it will continue with cout << "Max (20,10): " << Max(20,10) << endl;
old functionality.
cout << "Max (0,200): " << Max(0,200) << endl;
• To inline a function, place the keyword
inline before the function name and define cout << "Max (100,1010): " << Max(100,1010) <<
the function before any calls are made to the endl;
function. The compiler can ignore the inline return 0;
qualifier in case defined function is more than
a line. }
• A function definition in a class definition is an • When the above code is compiled and executed, it
inline function definition, even without the use
of the inline specifier. produces the following result
• Max (20,10): 20
• Max (0,200): 200
• Max (100,1010): 1010
Function Overloading
• Function overloading is a C++ programming feature that allows us to have more than one
function having same name but different parameter list, it means the data type and
sequence of the parameters.
• For example the parameters list of functions
myfuncn(int a, float b) &
myfuncn(float a, int b)
• are (int, float) and (float, int) which have different parameter list. Function overloading is
a compile-time polymorphism.
• To know the rules of overloading: we can have following functions in the same scope.
sum(int num1, int num2)
sum(int num1, int num2, int num3)
sum(int num1, double num2)
• The easiest way to remember this rule is that the parameters should qualify any one or
more of the following conditions, they should have different type, number or sequence of
parameters.
Function Overloading Rules
Rules :
• These two functions have different parameter type:
sum(int num1, int num2)
sum(double num1, double num2)
• These two have different number of parameters:
sum(int num1, int num2)
sum(int num1, int num2, int num3)
• These two have different sequence of parameters:
sum(int num1, double num2)
sum(double num1, int num2)
• All of the above three cases are valid case of overloading. We can have any number of
functions, just remember that the parameter list should be different.
• These two have same sequence of parameters but different return type:
int sum(int, int)
double sum(int, int)
• This is not allowed as the parameter list is same. Even though they have different return
types, its not valid.
Function Overloading Example
#include <iostream> #include <iostream>
using namespace std; using namespace std;
class Addition { class DemoClass {
public: public:
int sum(int num1,int num2) { int demoFunction(int i) {
return num1+num2; } return i;
int sum(int num1,int num2, int num3) { }
return num1+num2+num3; } double demoFunction(double d) {
}; return d; }
int main(void) { };
Addition obj; int main(void) {
DemoClass obj;
cout<<obj.sum(20, 15)<<endl;
cout<<obj.demoFunction(100)<<endl;
cout<<obj.sum(81, 100, 10); cout<<obj.demoFunction(5005.516);
return 0; } return 0; }
• The output of the program is: • The output of the program is:
35 100
5006.52
191
Advantages of Function Overloading
• The main advantage of function overloading is to the improve
the code readability and allows code reusability. In the example,
we have seen how we were able to have more than one function
for the same task(addition) with different parameters, this
allowed us to add two integer numbers as well as three integer
numbers, if we wanted we could have some more functions with
same name and four or five arguments.
• Imagine if we didn’t have function overloading, we either have
the limitation to add only two integers or we had to write
different name functions for the same task addition, this would
reduce the code readability and reusability.

You might also like