Chapter 1. Functions in C++
Chapter 1. Functions in C++
Functions in C++
Email: [email protected]
1
Course Content
➢Basic concept and need of function
4
Why we need function?
⇒ More manageable
⇒ Code are easier to maintain
⇒ Reduction in program size.
⇒ Code duplication is avoided.
⇒ Code reusability is provided.
⇒ Functions can be called repetitively.
⇒ Increase program readability.
⇒ Divide a complex problem into many simpler problems.
⇒ Reduce chances of error.
⇒ Makes modifying a program becomes easier.
⇒ Makes unit testing possible.
5
When we need function?
When you need to repeat the same process over and
over in a program.
6
Types of function
1. Built in functions/pre-defined function
are part of compiler package.
header file.
User needs to include pre-defined header file
(i.e. math.h, time.h)
functions such as
9
Types of function Cont’d… Example
#include<iostream> int stringLength(char x[])
using namespace std; {
int i=0, count=0;
int stringLength(char []);
while(x[i] )
int main() {
{ count++;
int len; i++;
char str[80]; }
cout<<"Enter the string: "; return count;
}
cin.getline(str, 80);
len = stringLength(str);
cout<<"\nLength = "<<len;
cout<<endl;
return 0;
}
10
Types of User defined function
❑ user-defined functions can be categorized as:
• void add(void);
• int add(void);
• void add(int,int);
11 • int add(int,int);
Function - Elements
12
Function Declaration/Prototype
❑ A function prototype is a declaration of a function that
void add(void);
int add(float,int);
❑ The names of parameters may or may not be given in the
prototype, however the names are necessary in the head of
function in the function definition.
❑ No function can be declared within the body of another
13
function.
Function Definition
❑ Syntax:
return_type function_name(data_type variable1, data_type variable2,..)
{ //function body
.............
Statements
.............
return( variable);
}
14
Function Definition Cont’d…
15
Function Call
16
Function Call Cont’d…
17
Function Call Cont’d…
❑ Names (not the types) of variables in function
declaration, function call and function definition may
vary.
❑ Arguments may be passed in the form of expressions
to the called function.
❑ In such a case, arguments are first evaluated and
converted to the type of formal parameter and then
the body of the function gets executed.
❑ If the return type of the function is not void, then
the value returned by the called function may be
assigned to some variable as given below.
variable_name = function_name(variable1, variable2, ...);
18
Function Call Cont’d…
❑ The terms calling function and called function are derived
from the telephone communication. The one who rings the
number is the calling person and one who receives the call is
the one called. The same terminology applies to functions.
❑ Thus the function which calls another function is the calling
function and the function which is called is the called
function.
❑ The different data variables that a function accepts for
processing are called parameters of the function.
❑ The values that represent the parameters and are passed on
to the function when it is called, are the arguments of the
function.
❑ Some functions return a numeric value to the calling function.
These are called return type functions. If a function does
19
not return a numeric value we call it void function.
Function Call Cont’d…
➢ Given the next program, which function is the calling function and
which is the called function?
#include<iostream.h>
#include<conio.h>
void nextMsg();
int main()
{
cout<< “Hello!\n”;
nextMsg();
cout<<“World\n”;
return 0;
}
void nextMsg() {
cout<< “GoodBye!\n”;
20 return; }
Return Statement
➢ The return statement is used to terminate the
execution of a function and return control to the
calling function.
➢ When the return statement is encountered, the
program execution resumes in the calling function at
the point immediately following the function call.
➢ A return statement may or may not return a value to
the calling function.
Syntax: return <expression> ;
➢ The value of expression, if present, is returned to the
calling
➢ function. However, in case expression is omitted, the
21 return value of the function is undefined.
Return Statement
➢ The return statement is used to terminate the
execution of a function and return control to the
calling function.
➢ When the return statement is encountered, the
program execution resumes in the calling function at
the point immediately following the function call.
➢ A return statement may or may not return a value to
the calling function.
Syntax: return <expression> ;
➢ The value of expression, if present, is returned to the
calling
➢ function. However, in case expression is omitted, the
22 return value of the function is undefined.
Passing Parameters To The Function
➢ There are two ways in which arguments(parameters)
can be passed to the called function.
24
Call by value Cont’d…
For instance:
#.....
void Foo(int num)
{
Num = 0;
cout<< “num = ” << num << “ \n”;
}
int main(void)
{
int x = 10;
Foo(x);
cout<< “x = ”<<x<< “\n”;
getch();
return 0;
25
}
Call by value Cont’d…
▪ When the function is called and x passed to it, num
Num = 0
x = 10
▪ Passing arguments in this way, where the function creates
26
Call by value Cont’d…
/* program to illustrate the concept of call by value */
#include<iostream.h>
#include<conio.h>
void add(int,int);
int main()
{
int a,b;
30
Call by Reference Cont’d…
void Foo(int & num)
{
num = 0;
cout<< “num = ” << num << “ \n”;
}
int main(void)
{
int x = 10;
Foo(x);
cout<< “x = ”<<x<< “\n”;
getch();
return 0;
}
31
Call by Reference Cont’d…
32
Function With Default Arguments
arguments.
➢ In such cases, the function assigns a default value to
33
Function With Default Arguments Cont’d…
Example : float result(int marks1, int marks2, int marks3=75);
average = result(60,70);
passes the value 60 to marks1, 70 to marks2 and lets
the function use default value of 75 for marks3.
▪ The function call
average = result(60,70,80);
passes the value 80 to marks3.
34
Function With Default Arguments Cont’d…
➢ Example
using namespace std;
void fun(int a=10, int b=20); //Declaration
OUTPUT
int main()
{
a: 3
fun(3,5);//Function Calling b: 5
fun(3);//Function Calling a: 3
fun();//Function Calling
return 0; b: 20
} a: 10
void fun(int a, int b)//Definition
{
b: 20
cout<<"a:"<<a<<endl;
cout<<"b:"<<b<<endl;
35
}
Global versus Local variables
Local Variable
➢ A variable defined inside a function (defined inside
function body between braces) is called a local
variable or automatic variable.
➢ Its scope is only limited to the function where it is
defined. In simple terms, local variable exists and can
be accessed only inside a function.
➢ The life of a local variable ends (It is destroyed)
when the function exits.
➢ Each block in a program defines a local scope. Thus
the body of a function represents a local scope. The
parameters of a function have the same scope as the
36 function body.
Global versus Local variables Cont’d…
Global Variable
38
Global versus Local variables Cont’d…
✓ N.B. if local variables are static, their values remain in case the
46
function is called again.
Overloading Function
49 factorial of n- 1.
Recursion Function
return n = = 0 ? 1 : n * factrial(n-1);
50
Recursion Function
53
that converges on the base case
Recursion versus iteration
call overhead.
Syntax:
inline return-type function-name(parameters)
{
// function code
}
56
Inline Function
while)
o If a function contains static variables.
o If a function is recursive.
int intArray[100];
SomeFunction(intArray, 100);
60
Example: Passing Single array to a function
int main()
{
int myArr[] = {1, 2, 3};
arr(myArr[1]); // pass array element myArr[1] only.
return 0;
}
61
Example: Passing 1D arrays to a function
#include <iostream>
using namespace std;
int SumValues (int [], int ); //function prototype
void main( )
{
int Array[10]={0,1,2,3,4,5,6,7,8,9};
int total_sum;
total_sum = SumValues (Array, 10); //function call
cout <<”Total sum is “ <<total_sum;
}
int SumValues (int values[], int num_of_values) //function header
{
int sum = 0;
for( int i=0; i < num_of_values; i++)
sum+=values[i];
return sum;
62
}
Example: Passing 2D arrays to a function
64