• No results found

Chapter 5: User-Defined Functions

N/A
N/A
Protected

Academic year: 2020

Share "Chapter 5: User-Defined Functions"

Copied!
50
0
0

Loading.... (view fulltext now)

Full text

(1)

Chapter 5:

User-Defined Functions

(2)

Objectives

In this chapter, you will learn about:

– Predefined functions and user-defined functions

– How to construct and use a, user-defined function that returns a value

– Function prototypes and function overloading – The scope of an identifier

– The difference between local and global identifiers

– Static variables

(3)

Introduction

Functions, or modules, or methods:

•Refer to a group of instructions which perform a specific task.

•They are like miniature programs that can be combined to form larger programs

Benefits:

•They allow complicated programs to be divided into manageable pieces

•Reuse of code

(4)

A Function

• In C++, a function is similar to that of a function in algebra

– It has a name

– It does some computation

• Example:

int add (int a, int b) {

return a + b; // Return statement

}

(5)

Two types of functions

• Depending on whether a function is predefined or created by programmer:

1.Library (predefined) Function.

A library is a set of built-in functions.

A programmer can use library function by invoking the function directly; no need to write it. That function is

already made ready from other programmers, you simply use it.

2.User-defined Function.

C++ allows programmer to define their own function.

(6)

Examples of standard libraries

Reference: https://en.cppreference.com/w/cpp/header

• <ctime>

• <climits>

• <exception>

• <cerrno>

• <string>

• <iostream>

• <fstream>

• <random>

• <map>

• <cmath>

Open source libraries list:

http://www.enseignement.polytechnique.fr/informatique/INF478/docs/Cpp/en/cpp/links/libs.html

(7)

Predefined Functions

• Some of the predefined mathematical functions, part of the cmath library, are:

sqrt(x) pow(x,y) floor(x)

• Every valid C++ program has at least one

function, that is main() function.

(8)

Predefined Functions (cont'd.)

• Predefined functions are organized into separate libraries

– I/O functions are in iostream header – Math functions are in cmath header

• To use predefined functions, you must include the header file using an include statement

#include <iostream>

#include <cmath>

(9)

Table 6-1: common predefined functions

(10)

Table 6-1: common predefined functions

(11)

Example 1: predefined function sqrt()

#include <iostream>

#include <cmath>

using namespace std;

int main()

{ double number, squareRoot;

cout << "Enter a positive number: ";

cin >> number;

// sqrt() is a library function to calculate square root squareRoot = sqrt(number);

cout << "Square root of " << number << " = " << squareRoot;

return 0;

}

(12)

User-Defined Functions

• How user-defined function works in C++ Programming?

When a program begins running, the system calls the main() function, that is, the system starts executing codes from main() function.

When control of the program reaches to function_name() inside main(), it moves to void function_name() and all code inside void function_name() is executed.

Then, control of the program moves back to the main function where the code after the call to the function_name() is executed.

(13)

Example 2: User Defined Function

• C++ program to add two integers.

Make a function add() to add integers and

display sum in main() function.

(14)

Function Definition

• Function definition refers to the set of instructions (the task) that the function will perform:

int add (int a,int b) { int add;

add = a + b;

return add;

}

• When the function is called from main(), control is transferred to the first statement of the function body. Then, statements are executed sequentially.

• When all the code inside function definition is executed, control of program moves to the calling function.

(15)

Function prototype (declaration)

• In C++, function prototype is a declaration of function without its body to give compiler information about user-defined function. Function prototype in the

above example is:

int add (int, int);

You can also declare function prototype as below but it's not necessary to write arguments (names of the variables).

int add(int a, int b);

• Note: It is used only if function definition code is written after main(); not necessary to define prototype if the function is defined before main().

(16)

Passing Arguments to Function

• In programming, argument (parameter) refers to the data which is passed to a function (function

definition) while calling it.

• In the above example, two variables num1 and num2 are passed to function during function call.

These arguments are known as actual arguments.

• The value of num1 and num2 are initialized to

variables a and b respectively. These arguments, a

and b, are called formal arguments.

(17)

Notes on passing arguments

• The numbers of actual arguments and formals argument should be the same.

• The type of first actual argument should match the type of first formal argument. The type of second actual argument should match the type of second formal argument and so on.

• In the example, both arguments are of int type. But it's not

necessary to have both arguments of same type.

(18)

Return Statement

• A function can return a single value to the calling program using return statement.

• In the example, the value of add is returned from the add function to the calling program using:

return add;

• The int before add(int a, int b)

means the function should return

a value of type int.

(19)

Return Statement

• Value-returning functions: have a return type

– Return a value of a specific data type using the return statement

• Void functions: do not have a return type

– Do not use a return statement to return a value

• Any code that is written after a return statement is discarded, as return gives control to the calling

function. It passes the returned value outside the

function.

(20)

Syntax: return Statement

• Syntax:

• In C++, return is a reserved word

• When a return statement executes

– Function immediately terminates – Control goes back to the caller

• When a return statement executes in the

function main, the program terminates

(21)

Syntax: return Statement (cont’d.)

(22)

Value-Returning Functions: Some

Peculiarities

(23)

Value-Returning Functions: Some

Peculiarities (cont’d.)

(24)

Value-Returning Functions

• To use these functions, you must know the following items:

• Name of the function

• Number of parameters, if any

• Data type of each parameter

• Data type of the value returned: called the type of the function

• The value returned by a value-returning function can be used by:

• Saving it for further calculation

• Using it in some calculation

(25)

Syntax: Formal Parameter List

(26)

Function Call

• Syntax to call a value-returning function:

• To execute the codes of function body, the user-defined function needs to be

invoked(called).

add(num1,num2);

main() function calls add() function

(27)

Syntax: Actual Parameter List

• Syntax of the actual parameter list:

• Formal parameter list can be empty:

• A call to a value-returning function with an

empty formal parameter list is:

(28)

Flow of Compilation and Execution

• Execution always begins at the first statement in the function main

• Other functions are executed only when called

• Function prototypes appear before any function definition

– Compiler translates these first

• Compiler can then correctly translate a

function call

(29)

Flow of Compilation and Execution (cont’d.)

• Function call transfers control to the first

statement in the body of the called function

• When the end of a called function is executed, control is passed back to the point immediately following the function call

– Function’s returned value replaces the function

call statement

(30)

Void Functions

• User-defined void functions can be placed either before or after the function main

• If user-defined void functions are placed after the function main

– The function prototype must be placed before the function main

• Void function does not have a return type

– return statement without any value is typically

used to exit the function early

(31)

Void Functions (cont’d.)

• Formal parameters are optional

• A call to a void function is a stand-alone statement; e.g. display(y);

• Void function definition syntax:

(32)

 Scope of an Identifier

• Scope of an identifier: where in the program the identifier is accessible

• Local identifier: identifiers declared within a function (or block)

• Global identifier: identifiers declared outside of every function definition

• C++ does not allow nested functions

– Definition of one function cannot be included in the body of another function

(33)
(34)

Global Variables and Side Effects

• Using global variables causes side effects

• A function that uses global variables is not independent

• If more than one function uses the same global variable:

– Can be difficult to debug problems with it

– Problems caused in one area of the program may

appear to be from another area

(35)

Static and Automatic Variables

• Automatic variable: memory is allocated at block entry and deallocated at block exit

– By default, variables declared within a block are automatic variables

• Static variable: memory remains allocated as long as the program executes

– Global variables declared outside of any block are

static variables

(36)

Static and Automatic Variables (cont’d.)

• Can declare a static variable within a block by using the reserved word static

• Syntax:

• Static variables declared within a block are local to the block

– Have same scope as any other local identifier in

that block

(37)

 Function Overloading:

(38)

Function Overloading:

An Introduction

• In a C++ program, several functions can have the same name

• Function overloading: allows creating several functions with the same name but different formal parameter list of the function

• The return type of the function doesn’t matter.

• Two functions are said to have different formal parameter lists if both functions have either:

– A different number of formal parameters

– If the number of formal parameters is the same, but the data type of the formal parameters differs in at least one position

(39)

Function Overloading (cont’d.)

• Overloaded functions may or may not have different return type but it should have different argument(s).

int test(int a) { }

double test(int b){ } //gives an error

The number and type of arguments passed to these

two functions are same even though the return type

is different. Hence, the compiler will throw error.

(40)

Recursive function

• Recursive function – it calls itself.

• The technique is called recursion.

(41)

Recursive Definitions (cont’d.)

• Recursive definition: defining a problem in terms of a smaller version of itself

• Base case: the case for which the solution is obtained directly

– Every recursive definition must have one (or more) base case(s)

– The base case stops the recursion

• General case: must eventually reduce to a base

case

(42)

Recursive Definitions (cont’d.)

• Example: factorials

0! = 1 (1)

n! = n x (n-1)! if n > 0 (2)

– Equation (1) is called the base case

– Equation (2) is called the general case

(43)

Recursive Definitions (cont’d.)

• Recursive algorithm: finds a solution by

reducing problem to smaller versions of itself

– Must have one (or more) base cases

– General solution must eventually reduce to a base case

• Recursive function: a function that calls itself

• Recursive algorithms are implemented using

recursive functions

(44)

Recursive Definitions (cont’d.)

• Think of a recursive function as having infinitely many copies of itself

– Every call has its own code and its own set of parameters and local variables

– After completing a particular recursive call:

• Control goes back to the calling environment, the previous call

• Execution begins from the point immediately following the recursive call

(45)

How it works

• The recursion

continues until some condition is met.

• To prevent infinite recursion, if...else

statement (or similar approach) can be used where one branch

makes the recursive call

and other doesn't.

(46)

Example

(47)

How it works

(48)

Recursion or Iteration?

• There are usually two ways to solve a particular problem:

– Iteration (looping) – Recursion

• When choosing, must consider:

– Nature of the problem – Efficiency

– Iterative control structure: uses a loop to

repeat a set of statements

(49)

Recursion or Iteration? (cont’d.)

• Whenever a function is called

– Memory space for its formal parameters and (automatic) local variables is allocated

• When the function terminates

– That memory space is then deallocated

• Every (recursive) call has its own set of

parameters and (automatic) local variables

(50)

Recursion or Iteration? (cont’d.)

• A recursive function executes more slowly than its iterative counterpart

• Sometimes iterative solution is more obvious and easier to understand

• If the definition of a problem is inherently recursive, consider a recursive solution

• Overhead associated with executing a (recursive) function in terms of: Memory space and Computer time

• Today’s computers are fast, so the Overhead of a recursion function is not noticeable

Figure

Table 6-1: common predefined functions
Table 6-1: common predefined functions

References

Related documents

The astrological works of Adelard consist, first, of a translation of the first thirty~ nine propositions of a work falsely ascribed to Ptolemy, which is called in Greek

The aim of the investigations was to evaluate the accuracy of angular meas‐

Calculate the average rate of return for each stock during the 5-year period.. Assume that someone held a portfolio consisting of 50 percent of Stock A and 50 percent of Stock

Besides individual measurements, the device also supports parallel measurement via Probe 1 and Probe 2 for resistance, direct/alternating voltage, direct/alternating current, as well

Utilities restructured to avoid further risk contamination of their healthy assets (renewables and grid infrastructure) by the conventional power generation business (fossil fuel

However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access

A consequence of this perspective of woman directors being appointed as part of the symbolic management of the independence of the board is that, when these directors lose

[r]