0% found this document useful (0 votes)
109 views36 pages

C++ Function: Chapter-5

The document discusses functions in C++. It defines what a function is, its characteristics, why functions are used, and how to declare, define, call, and pass parameters to functions. It also covers function scope, static variables, and the scope resolution operator. Specifically: 1. A function is a block of code that performs a specific task and can be reused. Functions may take parameters and return values. 2. Functions are declared with a return type, name, and parameters. They are defined with a body of code. Parameters pass input and the return value provides output. 3. Functions organize code, are reusable, and make programs modular. Static variables remain in memory during the program execution

Uploaded by

Biya Kumilachew
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views36 pages

C++ Function: Chapter-5

The document discusses functions in C++. It defines what a function is, its characteristics, why functions are used, and how to declare, define, call, and pass parameters to functions. It also covers function scope, static variables, and the scope resolution operator. Specifically: 1. A function is a block of code that performs a specific task and can be reused. Functions may take parameters and return values. 2. Functions are declared with a return type, name, and parameters. They are defined with a body of code. Parameters pass input and the return value provides output. 3. Functions organize code, are reusable, and make programs modular. Static variables remain in memory during the program execution

Uploaded by

Biya Kumilachew
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

C++

Function

Chapter-5
Compiled by Mr. Abunu T.
Function
What is a function?
 A function is a self-contained program segment (block of segments) that performs some
specific well-defined task.
 A function allows complicated programs to be divided into manageable pieces
 a function is a group of statements that is given a name, and which can be called from some
point in the program.
 It can be a small task or a big task but the function will perform that task completely.
 Functions take some input as parameters and return the result as a return value.
 If we write a function then we can reuse it in the program
 In simple terms, a function is a block of code that only runs when it is called/invoked.
Cont.
Characteristics of functions
 Functions are identified by their name.
 A function can take 0 or more parameters means it may not take any input.
 A function may or may not return a value but it can return at most one value.
 It cannot return multiple values but it can take multiple values as parameters.
 If the function is not returning any value, then the return type should be void.
 The rules for giving function names are the same as the rules for giving the
variable names. Same rules you should follow for giving function names also
Cont..

Why use functions


 It makes the program clear and easy to understand.
 Single functions can be tested easily for errors.
 It helps to modify the program easily without changing the structure of a
program
 Code Re-usability
 Develop an application in module format.
 Code optimization: No need to write a lot of code
Declaring, Defining, and Calling functions

Declaring functions
 It consists of three entities:
 The function return type.
 This specifies the type of value the function returns. A function that returns nothing should
have a return type void
 The function name.
 this is simply a unique identifier
 The function parameters (also called its signature).
 This is a set of zero or more typed identifiers used for passing values to and from the function.
Cont..
How to write a function in C++?
 First of all, the function should have a name. Then it should have a parameter list

or also called an argument list (the parameters it is taking), then the function
should have a return type
Return-type Function-name (Parameter-list)

Output Input
Almost one value 0 or more values
Cont..
Defining a function:
 A C++ function definition consists of a function header and a function body
 Here are all the parts of the function definition:
 Return Type − A function may return a value
 Function Name − This is the actual name of the function
 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 an actual parameter or argument. 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
Cont..
Calling the 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
 Using a function involves ‘calling’ it.
 Calling a function means making the instruction of the function to be executed.
 A function call consists of the function name followed by the call operator brackets ‘()’, inside
which zero or more comma-separated arguments appear.
 The number and type of arguments should match the number of function parameters.
 Each argument is an expression whose type should match the type of the corresponding
parameter in the function interface.
Cont..
Calling the function:
 When a function call is executed, the arguments are first evaluated and their resulting values
are assigned to the corresponding parameters.
 The function body is then executed. Finally, the return value (if any) is passed to the caller
Let’s see a simple example: void func1(); Prototype of a function declaration
int main()
{
func1(); function call
} Return type is void
void func1()
{
Function definition ----- statement Function body
}
Cont..
 Here we have a function called display() which will print Hello when it is
called. This function is taking no arguments. We have called this function inside
the main() function
 When the main function starts, it will come to the line where we have called the
display function, then the control will go to the display function, and then it will
execute the cout line.
 After executing the print line, the control will again return back and continue the
main function
Cont..
Argument
 An argument is referred to the values that are passed within a function when the
function is called.
 These values are generally the source of the function that requires the arguments
during the process of execution
 These values are assigned to the variables in the definition of the function that is
called.
 The type of the values passed in the function is the same as that of the variables
defined in the function definition.
Cont..
Parameters
 The parameter is referred to as the variables that are defined during a function
declaration or definition
 These variables are used to receive the arguments that are passed during a
function call
 These parameters within the function prototype are used during the execution of
the function for which it is defined
Cont..
 Example: Function for Adding Two Numbers in C++.

30 8
Parameter Passing Techniques in C++
Pass by Value
 Pass by value is a method in C++ to pass the values to the function arguments.
 In the case of pass-by-value the copies of actual parameters are sent to the formal parameter,
which means that if we change the values inside the function that will not affect the actual
values
O
ut
pu
Example 1: t

Before Swap: X:=4 Y:=5


After Swap: X:=4 Y:=5
Parameter Passing Techniques in C++
Pass/call by Value
 As shown in Example 1, we have initialized two integer variables “a” and “b” and printed
their values. Then we called a “swap” function and passed the values of variables “a” and “b”
and again printed the values of variables “a” and “b”.

Pass/call by Reference
 Pass by reference is a method in C++ to pass the values to the function arguments.
 In the case of call by reference, the reference of actual parameters is sent to the formal
parameter, which means that if we change the values inside the function that will affect the
actual values
Parameter Passing Techniques in C++
Pass/call by Reference
 Example -2

O
ut
pu
t
Before Swap: X:=4 Y:=5
After Swap: X:=5 Y:=4

 The values of “a” and “b” are swapped when the swap function is called. So the
main point here, is that when the call-by-reference method is used it changes the
actual values because references of actual values are sent to the function.
Cont.
What is a Scope?
 A scope is a region of a program and the scope specified where a variable can be
defined.
 The scope of the variable determines the lifetime of a variable. That means it is
determined in which block of code the variable is applicable or alive
 So, there are three places, where variables can be declared. They are as follows
1. Global variable
2. Local variable
3. Static variable
Cont.
Static Variables in C++
 A static variable is a variable that is declared using the keyword static.
 The space for the static variable is allocated only one time and this is used for the entirety of the
program.
 Once this variable is declared, it exists till the program executes. So, the lifetime of a static variable is
the lifetime of the program.
 They are just like a global Variable. Only the difference between global and static variables is global
variables can be accessed in any function and static variables are accessible only inside the function in
which they are declared.
 A static variable is not created every time we call a function. They are just created only once which is
at the loading time
Cont.

Ou
tp
Static Variables in C++

ut
10 1
10 2
10 3
Static variables Key Points
 They have a local scope but remain in memory throughout the execution of the program
 They are created in the code section
 They are history-sensitive
When to use Static Variable in C++?
 We should use a static variable whenever we want to reuse the modified value of the variable inside a function in
the next function call.
 When we want all the objects to maintain a single copy of the class variable
Scope resolution operator in C++
 To access a global variable when there is a local variable with the same name:
 If the global variable name is the same as the local variable name, the scope
resolution operator will be used to call the global variable
 Symbol of scope resolution operator is::

Ou
tpu
t

The Value of Age: 40


Scope resolution operator in C++

Ou
tpu
t

The Value of Age: 40


Local Variable: 40
Global Variable: 25
Inline Functions
 The inline functions are a C++ enhancement feature to increase the execution time of a
program.
 Inline functions are used to reduce the function call overhead. When one function is being
called multiple times in the program it increases the execution time, so an inline function is
used to reduce time and increase program efficiency.
 If the inline function is being used when the function is called, the inline function expands the
whole function code at the point of a function call, instead of running the function.
 Inline functions are considered to be used when the function is small otherwise it will not
perform well.
 Inline is not recommended when static variables are being used in the function
Inline Functions
inline return-type function-name(parameters)
Syntax {
// function code
}

Example
Ou
t
pu
t

The cube of 3 is : 27
Inline Functions
Advantages of inline functions
 Function call overhead doesn’t occur.
 It also saves the overhead of push/pop variables on the stack when the function is
called.
 It also saves the overhead of a return call from a function.
Default Arguments in C++
 A default argument is a value provided in a function declaration that is automatically assigned
by the compiler if the calling function doesn’t provide a value for the argument.
 In case any value is passed, the default value is overridden
 Default argument is a programming convenience that removes the burden of having to specify
argument values for all function parameters
N.B: Once we provide a default value for a parameter, all subsequent parameters must also have
default values: void add(int a, int b = 3, int c, int d); Invalid
void add(int a, int b = 3, int c, int d = 4);

void add(int a, int c, int b = 3, int d = 4); Valid


Default Arguments in C++
 Example:

Ou
tpu
t
Sum=: 10
Sum:= 25
Sum=: 45
 In this case parameters b & c have default values of 0, but when the argument is passed the
default values will be overridden by the new argument value.
Default Arguments in C++
Characteristics for defining the default arguments:
 The values passed in the default arguments are not constant. These values can be
overwritten if the value is passed to the function. If not, the previously declared
value retains.
 During the calling of the function, the values are copied from left to right.
 All the values that will be given default value should be on the right.
Function Overloading in C++
 Function overloading is a process to make more than one function with the same name but
different parameters, numbers, or sequences.
 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.
 The easiest way to remember this rule is that the parameters should qualify any one or more of
the following conditions, they should have a different type, number, or sequence of parameters.
 For example:
 These two functions have different parameter types:
sum(int num1, int num2)
sum(double num1, double num2)
Function Overloading in C++
 These two have a different number of parameters:

sum(int num1, int num2)


sum(int num1, int num2, int num3)

 These two have a different sequence of parameters:

sum(int num1, double num2)


sum(double num1, int num2)

 N.B: All of the above three cases are a valid cases of overloading
Function Overloading in C++
 Example:

sum = 12
sum = 11.5
 In the above example two functions have the same function names with different parameter
types, however, the output values are different.
Recursion Function
 Recursion is a method in C++ that calls itself directly or indirectly until a
suitable condition is satisfied.
 In this method, we repeatedly call the function within the same function, and it
has a base case and a recursive condition
 The recursive condition helps in the repetition of code again and again, and the
base case helps in the termination of the condition.
 If there is no base case in the recursive function, the recursive function will
continue to repeat continuously.
Recursion Function
int recursion(n)
{
if(n==0)
return;
}
return(n-1);
}
 Here, n==0 is the base case that will terminate the iteration of the function when
n becomes equal to zero.
 return(n-1) is the recursive function that will help in the repetition of code.
Recursion Function
 Working on Recursion
 Recursion performs a number of repetitive calls to the function from within the
function.
 The recursive condition performs the repeating calls to the function until the base
case is met
 The base case is present inside the function, and once the condition of the base
case is satisfied, it stops the execution.
 Let’s understand it with a simple example.
Recursion Function
 Example: Factorial of 5
return 5*factorial(4) = 120
return 4*factorial(3) = 24
return 3*factorial(2)=6
return 2*factorial(1) = 2
return 1*factorial(0) = 1
 In the factorial function, we have to perform many repetitive calls to the
function. In this example, the recursive condition would be n*factorial(n-1);
factorial is the function's name, and the value of n is 5.
Recursion Function

Enter a non-negative number: 4


Factorial of 4 = 24
THANK YOU
!
Any Questions??

You can find me at


[email protected]
[email protected]

You might also like