Unit 4 - C++ Functions

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 61

202000212

Object Oriented
Programming

Unit - 4
C++ Functions

A.Y. 2022-23 (Even) Semester: 2


(Branch - IoT)
(Course Code: 202000212)

Vinita Shah
Asst. Professor, IT Dept., GCET
C++ Functions
C++ Function
▪ A function is a group of statements that together perform a task.
▪ Functions are made for code reusability and for saving time and
space.
Function

I like C++ so much


Library Function User Defined Function
I like Rupesh sir
Predefined Created by User
Declarations inside header files Programmer need to declare it
Eg. printf() – stdio.h Eg. factorial()
pow() – cmath.h areaofcircle()
strcmp() – cstring.h

Unit – 4 C++ Functions 3


C++ Function – (Cont…)
▪ There are three elements of user defined function

void func1(); Function Declaration


void main()
{
....
func1(); I like C++ soFunction
much call
}
void func1() I like Rupesh sir
{
.... Function
Function
definition
.... body
}

Unit – 4 C++ Functions 4


Simple Function – (Cont…)
▪ Function Declaration
Syntax:
return-type function-name (arg-1, arg 2, …);
Example: int addition(int , int );

▪ Function Definition
Syntax:
return-type function-name (arg-1, arg 2, …)
{
... Function body
}
Example: int addition(int x, int y)
{
return x+y;
}
Categories of Function
(1) Function with arguments and returns value

(2) Function with arguments but no return value

I like C++ so much


(3) Function with no argument but returns value

I like Rupesh sir


(4) Function with no argument and no return value

Unit – 4 C++ Functions 6


Categories of Function
(1) Function with arguments and returns value
Function arguments/
parameters

Return type int func1(int , int ); \\declaration


void main()

Function func1
{ I like C++ so much
....
returns integer value
to variable z
I like Rupesh sir
int z = func1(5,6); \\function call
}
int func1(int a, int b) \\definition
{
....
return a+b;
} returns a+b to calling function
Unit – 4 C++ Functions 7
Categories of Function (Cont…)
(2) Function with arguments but no return value

void func1(int , int ); \\function declaration


void main()
{
.... I like C++ so much
func1(5,6); \\function call
} I like Rupesh sir
void func1(int a, int b) \\function definition
{
....
....
}

Unit – 4 C++ Functions 8


Categories of Function (Cont..)
(3) Function with no argument but returns value

int func1();
void main()
{
....
int z = func1();
I like C++ so much
}
int func1()
I like Rupesh sir
{
....
return 99;
}

Unit – 4 C++ Functions 9


Categories of Function (Cont…)
(4) Function with no argument and no return value
void func1();
void main()
{
....
func1();
I like C++ so much
}
void func1()
I like Rupesh sir
{
....
....
}

Unit – 4 C++ Functions 10


Program: Categories of function
▪ Write C++ programs to demonstrate various categories of
function, Create function addition for all categories.

I like C++ so much


I like Rupesh sir

Unit – 4 C++ Functions 11


Function with argument and returns value
#include <iostream> Value of
using namespace std; int main() Argument int fun1(int f)
{ {
..... .....
int add(int, int); b = fun1(a); .....
..... return e;
int main(){
int a=5,b=6,ans;
I like C++ so much
} Function
Result
}

ans = add(a,b);
I like Rupesh sir
cout<<"Addition is="<<ans;
return 0;
}
int add(int x,int y)
{
return x+y;
}
Unit – 4 C++ Functions 12
Function with arguments but no return value
#include <iostream>
Value of
using namespace std; int main() Argument void fun1(int f)
{ {
..... .....
void add(int, int); fun1(a); .....
int main() ..... .....
{ I like C++ so much
} No Return
value
}
int a=5,b=6;
add(a,b); I like Rupesh sir
return 0;
}
void add(int x,int y)
{
cout<<"Addition is="<<x+y;
}
Unit – 4 C++ Functions 13
Function with no argument but returns value

int add(); No
int main() Input int fun1()
{ {
int main() ..... .....
{ b = fun1(); .....
..... return e;
int ans;
ans = add();
I like C++ so much
} Function
Result
}

I like Rupesh sir


cout<<"Addition is="<<ans;
return 0;
}
void add()
{
int a=5,b=6;
return a+b;
}
Unit – 4 C++ Functions 14
Function with no argument and no return value
void add();
No
int main() Input void fun1()
int main() { {
{ ..... .....
fun1(); .....
add(); ..... .....
return 0; I like C++ so much
} No Return }
} value
void add() I like Rupesh sir
{
int a=5,b=6;
cout<<"Addition is="<<a+b;
}

Unit – 4 C++ Functions 15


Categories of Functions Summary
(1) Function with argument and returns value
Value of
int main() Argument int fun1(int f)
{ {
..... .....
b = fun1(a); .....

I like C++ so much


}
.....
Function
Result
}
return e;

I like
(2) Function with Rupesh
argument sir value
and but no return
Value of
int main() Argument void fun1(int f)
{ {
..... .....
fun1(a); .....
..... .....
} No Return }
value

Unit – 4 C++ Functions 16


Categories of Functions Summary
(3) Function with no argument and returns value
No
int main() Input int fun1()
{ {
..... .....
b = fun1(); .....

I like C++ so much


}
.....
Function
Result
}
return e;

I like
(4) Function with Rupesh
no argument sir
and but no return value
No
int main() Input void fun1()
{ {
..... .....
fun1(); .....
..... .....
} No Return }
value
Unit – 4 C++ Functions 17
Call by Reference
No. Call by value Call by reference

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


1
function function

Changes made inside the function is Changes made inside the function is
2
not reflected on other functions reflected outside the function also

Actual and formal arguments will be


Actual and formal arguments will be
3 created in different memory
created in same memory location
location
Call by value
▪ In call by value, original value is not modified.

▪ In call by value, value being passed to the function is locally


stored by the function parameter in stack memory location.
I like C++ so much
▪ If you change the value of function parameter, it is changed for
I likeonly.
the current function Rupesh sir the value of variable
It will not change
inside the caller method such as main().

Unit – 4 C++ Functions 21


Call by value
#include <iostream>
using namespace std;
void change(int data);
int main()
{
int data = 3;
change(data); I like C++ so much
cout << "Value of the data is: " << data<< endl;
return 0;
} I like Rupesh sir
void change(int data)
{
data = 5;
}

Unit – 4 C++ Functions 22


Call by reference
▪ In call by reference, original value is modified because we pass
reference (address).

▪ Here, address of the value is passed in the function, so actual


I like C++ so much
and formal arguments share the same address space.

Hence, valueIchanged
▪ like Rupesh siris reflected inside as
inside the function,
well as outside the function.

Unit – 4 C++ Functions 23


Call by reference – swap 2 numbers
#include <iostream>
using namespace std;
void swap (int*x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp; I like C++ so much
}
I like Rupesh
int main()
sir
{
int x=500, y=100;
swap(&x, &y);
cout<<"Value of x is: "<<x<<endl;
cout<<"Value of y is: "<<y<<endl;
return 0;
}
Unit – 4 C++ Functions 24
Program: Swap using pointer, reference
▪ Write a C++ program that to swap two values using function
1. With pass by pointer
2. With pass by reference

I like C++ so much


I like Rupesh sir

Unit – 4 C++ Functions 25


Program: Solution
void swapptr(int *x, int *y)
{
int z = *x; ▪ Pointers as arguments
*x=*y;
*y=z; ▪ References as
arguments
} I like C++ so much
void swapref(int &x, int &y)
{
int z = x;
I like Rupesh sir
int main()
x = y; {
y = z; ...
} swapptr(&a,&b);
swapref(a,b);
...
}
Unit – 4 C++ Functions 26
Program: Solution
void swapptr(int *, int *);
void swapref(int &, int &);
int main()
{
int a = 45;
int b = 35;
cout<<"Before Swap\n";
cout<<"a="<<a<<" b="<<b<<"\n";

swapptr(&a,&b);
cout<<"After Swap with pass by pointer\n";
cout<<"a="<<a<<" b="<<b<<"\n";

swapref(a,b);
cout<<"After Swap with pass by reference\n";
cout<<"a="<<a<<" b="<<b<<"\n";
}
Program: Solution (Cont…)
void swapptr(int *x, int *y)
{
int z = *x;
*x=*y;
*y=z;
} I like C++ so much
void swapref(int &x, int &y)
{ I likeOUTPUT
Rupesh sir
int z = x;
Before Swap
x = y;
a=45 b=35
y = z;
After Swap with pass by pointer
}
a=35 b=45
After Swap with pass by reference
a=45 b=35
Unit – 4 C++ Functions 28
Program: Return by Reference
▪ Write a C++ program to return reference of maximum of two
numbers from function max.

I like C++ so much


I like Rupesh sir

Unit – 4 C++ Functions 29


Program: Solution
int& max(int &, int &);
int main() ▪ Function declaration
{ returning reference
int a=5,b=6,ans;
ans = max(a,b);
I like C++ so much
cout<<"Maximum="<<ans;
}
int& max(int &x,int &y)I like Rupesh sir
{
if (x>y)
return x;
else
return y;
}
Unit – 4 C++ Functions 30
C Preprocessors
Macros
C Preprocessors Macros
▪ C Preprocessor is a text substitution in program.
▪ It instructs the compiler to do pre-processing before the actual
compilation.
▪ Macros are a piece of code in a program which is given some
name. I like C++ so much
▪ Whenever this name is encountered by the compiler the compiler
replaces the Iname
like
withRupesh sir
the actual piece of code.
▪ The '#define' directive is used to define a macro.
▪ Syntax -
• #define macro-name replacement-text

Unit – 4 C++ Functions 32


C Preprocessor Macro Example

#include <iostream>
using namespace std;

#define PI 3.1415
I like C++ so much
int main()
{ I like Rupesh sir
cout << "Value of PI :" << PI << endl;
return 0;
}

Unit – 4 C++ Functions 33


Preprocessor Macro Example
#include <iostream>
using namespace std;
#define PI 3.1415 Preprocessor
#define circleArea(r) (PI*r*r)
int main()
{
int radius; I like C++ so much
float area;
I like Rupesh sir
cout<<"Enter the radius: ";
cin>>radius;
area = circleArea(radius);
cout<<"Area = %f", area;
return 0;
▪ Every time the program encounters
} circleArea(argument), it is replaced by
(3.1415*(argument)*(argument)).
Unit – 4 C++ Functions 34
Preprocessor Macro Example
#include <iostream>
using namespace std;
#define MIN(a,b) (((a)<(b)) ? a : b)

int main()
{ I like C++ so much
int i, j;
I like Rupesh sir
i = 100;
j = 30;

cout <<"The minimum is " << MIN(i, j) << endl;


return 0;
}
Unit – 4 C++ Functions 35
Inline Functions
Inline Functions
▪ Every time a function is called it takes a lot of extra time to
execute series of instructions such as
1. Jumping to the function
2. Saving registers

I like C++ so much


3. Pushing arguments into stack
4. Returning to the calling function
I like Rupesh sir
▪ If a function body is small then overhead time is more than actual
code execution time so it becomes more time consuming.
▪ Preprocessor macros is a solution to the problem of small
functions in C.
▪ In C++, inline function is used to reduce the function call
overhead.

Unit – 4 C++ Functions 37


Inline Functions (Cont…)
Syntax:
inline return-type function-name(parameters)
{
// function code
}

I like C++ so much


▪ Add inline word before the function definition to convert simple
function to inline function.
Example: I like Rupesh sir
inline int Max(int x, int y)
{
if (x>y)
return x;
else
return y;
}
Unit – 4 C++ Functions 38
Program: Inline function
▪ Write a C++ program to create inline function that returns cube of
given number (i.e n=3, cube=(n*n*n)=27).

I like C++ so much


I like Rupesh sir

Unit – 4 C++ Functions 39


Program: Solution
#include <iostream>
using namespace std;

inline int cube(int s)


{
return s*s*s; I like C++ so much
}
int main() I like Rupesh sir
{
cout << "The cube of 3 is: " << cube(3);
return 0;
}
▪ Calls inline function cube with argument 3
Unit – 4 C++ Functions 40
Critical situations Inline Functions
▪ Some of the situations inline expansion may not work
1) If a loop, a switch or a goto exists in function body.
2) If function is not returning any value.
3) If function contains static variables.
I like C++ so much
4) If function is recursive.

I like Rupesh sir

Unit – 4 C++ Functions 41


Macro vs. Inline Function
Sr.
Inline Macro
No.
An inline function is defined by Whereas the macros are defined by
1.
the inline keyword. the #define keyword.

2.
I like C++ so much
Through inline function, the class’s data
members can be accessed.
Whereas macro can’t access the class’s
data members.

3. I like Rupesh sir


In the case of inline function, the
program can be easily debugged.
Whereas in the case of macros, the
program can’t be easily debugged.

Whereas in the case of macro, the


In the case of inline, the arguments are
4. arguments are evaluated every time
evaluated only once.
whenever macro is used in the program.

In C++, inline may be defined either Whereas the macro is all the time
5.
inside the class or outside the class. defined at the beginning of the program.

Unit – 4 C++ Functions 42


Macro vs. Inline Function
Sr.
Inline Macro
No.
In C++, inside the class, the short
6. length functions are automatically While the macro is specifically defined.
made the inline functions.

I like C++ so much


Inline function is terminated by the
While the macro is not terminated by
7. any symbol, it is terminated by a new
I like Rupesh sir
curly brace at the end.
line.

Unit – 4 C++ Functions 43


Function Overloading
Function Overloading
▪ Suppose we want to make functions that add 2 values, add 3
values , add 4 values
In C Function with
int sum(int a, int b); same name in a
I like C++ so much
int sum(int a, int b, int c);
int sum(int a, int b, int c, int d);
program is not
allowed in C
I like Rupesh sir language

In C++ Function with


int sum(int a, int b); same name in a
int sum(int a, int b, int c); program is
int sum(int a, int b, int c, int d); allowed in C++
language
Unit – 4 C++ Functions 45
Function overloading – Cont…
▪ C++ provides function overloading which allows to use multiple
functions sharing the same name .
▪ Function overloading is also known as Function Polymorphism in
OOP.
▪ It is the practice of declaring the same function with different
signatures. I like C++ so much
▪ However, theI two
like Rupesh
functions sir name must differ in at
with the same
least one of the following, Arguments
a) The number of arguments make the
b) The data type of arguments function
c) The order of appearance of arguments unique

▪ Function overloading does not depends on return type.

Unit – 4 C++ Functions 46


Function Overloading
int sum(int a, int b); Valid

float sum(int a, int b); Invalid

int sum(int a, int c); Invalid


I like C++ so much
int sum(int a, float b); Valid
I like
int sum(float Rupesh
b, int a); sir Valid

float sum(float a, float b); Valid

int sum(int a, int b, int c); Valid

int sum(int a, float b, int c); Valid

Unit – 4 C++ Functions 47


Program: Function overloading
▪ Write a C++ program to demonstrate function overloading. Create
function display() with different arguments but same name

I like C++ so much


I like Rupesh sir

Unit – 4 C++ Functions 48


Program: Solution (Cont…)
void display(int var)
{
cout << "Integer number: " << var << endl;
}
I like C++ so much
void display(float var)
{

} I like Rupesh sir


cout << "Float number: " << var << endl;

void display(int var1, float var2) {


cout << "Integer number: " << var1;
cout << " and float number:" << var2;
}

Unit – 4 C++ Functions 49


Program: Solution
int main()
{
int a = 5; float b = 5.5;
display(a);
display(b);
display(a, b); I like C++ so much
return 0;
} I like Rupesh sir

Unit – 4 C++ Functions 50


Program: Function overloading
▪ Write a C++ program to demonstrate function overloading. Create
function area() that calculates area of circle, triangle and box.

I like C++ so much


I like Rupesh sir

Unit – 4 C++ Functions 51


float area(int r)
{ Program #7
return 3.14*r*r; Solution
}
float area(int h, int b)
{
return 0.5*h*b;
}
I like C++ so much
float area(int l, int w, int h)
{
return l*w*h; I like Rupesh sir
}
int main(){
cout<<"area of circle="<<area(5);
cout<<“\n area of triangle="<<area(4,9);
cout<<“\n area of box="<<area(5,8,2);
return 0;
}
Unit – 4 C++ Functions 52
Default Function
Arguments
Default Function Argument

I like C++ so much


int cubevolume(int l=5, int w=6, int h=7)
{
return l*w*h;
} I like Rupesh sir
int main() Here, there can be
If argument fourspecified
is not types ofthen,
function
{ compiler lookscalls possible to see how
at declaration
cubevolume(); many arguments a function uses and
cubevolume(9);
alert program to use default values
cubevolume(15,12);
cubevolume(3,4,7);
}
Unit – 4 C++ Functions 54
Default Argument Example
int volume(int l=5,int w=6, int h=7)
{
return l*w*h;
}
int main() {
I like C++ so much
cout<<"volume="<<volume()<<endl;
cout<<"volume="<<volume(9)<<endl;
I like Rupesh sir
cout<<"volume="<<volume(15,2)<<endl;
cout<<"volume="<<volume(3,4,7)<<endl;
return 0;
}
▪ Function call passing
withoutonly
passing
all
two oneargument.
argument.
arguments.
arguments.
▪ Explicitly value5,6,7
Default value 9
3,4,7
15,2
passed to l.totol,w
considered
passed
passed for l,
l,w,h w, h respectively.
respectively.
respectively.
▪ Default value 6,7
7 considered
considered h w,h
for for respectively.
respectively.
Unit – 4 C++ Functions 55
Default Arguments
▪ while invoking a function If the argument/s are not passed then,
the default values are used.
▪ We must add default arguments from right to left.
▪ We cannot provide a default value to a particular argument in the
I like C++ so much
middle of an argument list.
▪ Default arguments are useful in situations where some arguments
always have Ithelike Rupesh sir
same value.

int cubevolume( int l = 2, int w = 2, int h = 2 )


{
return l*w*h;
}
Unit – 4 C++ Functions 56
Default Arguments (Cont…)
▪ Legal and illegal default arguments
void f(int a, int b, int c=0); Valid
void f(int a, int b=0, int c=0); Valid
void f(int a=0, int b, int c=0); Invalid
I like C++ so much
void f(int a=0, int b, int c); Invalid
void f(int a=0, int b=0, int c=0); Valid
I like Rupesh sir

Unit – 4 C++ Functions 57


Common Mistakes
(1) void add(int a, int b = 3, int c, int d = 4);

▪ You cannot miss a default argument in between two arguments.


▪ In this case, c should also be assigned a default value.

I like C++ so much


(2) void add(int a, int b = 3, int c, int d);
I like Rupesh sir
▪ If you want a single default argument, make sure the argument is
the last one.

Unit – 4 C++ Functions 58


Program: Default Arguments
▪ Write a C++ program to create function sum(), that performs
addition of 3 integers also demonstrate Default Arguments
concept.

I like C++ so much


I like Rupesh sir

Unit – 4 C++ Functions 59


Program: Default Arguments
#include <iostream>
using namespace std;
int sum(int x, int y=10, int z=20)
{
return (x+y+z);
} I like C++ so much
int main()
{ I like Rupesh sir
cout << "Sum is : " << sum(5) << endl;
cout << "Sum is : " << sum(5,15) << endl;
cout << "Sum is : " << sum(5,15,25) << endl;
return 0;
}

Unit – 4 C++ Functions 60


Thank You

You might also like