Top Banner
Chapter 9 Functions Dept of Computer Engineering Khon Kaen University
46

Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

Dec 13, 2015

Download

Documents

Elmer Johnston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

Chapter 9 Functions

Dept of Computer EngineeringKhon Kaen University

Page 2: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 2

Introduction Most useful programs are much

larger than the programs we have considered so far

To make large program manageable, programmers modularise them into subprograms

They can be compiled and tested separately and reused in different programs

Page 3: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 3

Standard C++ Library Functions

The standard C++ library is a collection of pre-defined functions and other program elements which are accessed through header files

Page 4: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 4

The Square Root Function

#include <cmath> // define sqrt() function#include <iostream> // define coutusing namespace std;int main() {

int x = 4;double y = sqrt(x);// calling a function by using its name cout << “sqrt(“ << x << “) = “ << y << endl;

}sqrt(4) = 2

Page 5: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 5

y = sqrt(x) The expression x in the () is called

the argument or actual parameter of the function call and we say that it is passed by value to the function

Black box

sqrt()main()

x4 4

22y

int

double

Page 6: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 6

Mathematical Functions Most of the mathematical functions

that you find on a pocket calculator are declared in the <cmath> header file.

The examples of these functions are sin(x), cos(x), tan(x), asin(x), acos(x), etc. floor(x), ceil(x) fabs(x), abs(x) sqrt(x), pow(x,p), log(x)

Page 7: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 7

Useful Header Files in C++

<cmath>: Defines mathematical functions

<cstdio>: Defines functions for standard input and output

<cstdlib>: Defines utility functions <cstring>: Defines functions for

processing strings <ctime>: Defines time and date functions To learn how to use functions in these

files, http://www.cplusplus.com/ref/

Page 8: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 8

User-defined Functions Programmers also need to be able to

define their own functions A user-defined function has two parts:

its head and its body The syntax of the head of a function is:

return-type func_name(parameter-list)

The body of a function is the block of code that follows its head

Page 9: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 9

Return Statement return expression; A functions’ return statement serves

two purposes: It terminates the execution of the

function It returns a value to the calling program

Where expression is any expression whose value could be assigned to a variable whose type is the same as the function’s return type

Page 10: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 10

Sample User-Defined Function

int cube(int x){

return x*x*x;} What is each part of the function

called? What is returned from executing

‘cube(2)’? Can the function return nothing?

Page 11: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 11

Test Drivers Whenever you create your own

functions, you should immediately test it with a simple program

Such program is called a test driver Why do we need to immediately test

each function that we just define? What is the main concept behind

designing a test driver?

Page 12: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 12

Sample Test Driverint cube(int x) { return x*x*x;}int main() {

int n = 1;while (n != 0)

{cin >> n;cout << “\tcube(“ << n << “) = “

<< cube(n) << endl; }} What is the output if n = 2, 3, 4? Can we write a better program?

Page 13: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 13

Sample Test Driverint max(int x, int y) { // return a larger #

if (x < y) return y; else return x; }int main() { // test the max() function

int m, n;do {

cin >> m >> n;cout << “max (“ << m << “,” << n

<<“) = “ << max(m,n) << endl; } while (m != 0);}

Page 14: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 14

Function Declaration & Definition

Function declaration lists only the header of the function to provide the compiler with all information it needs to compile the rest of the function Ex: int max(int m, int n)

Function definition needs to include both the header and the body of the function Ex: int max(int m, int n) { if (x < y) return

y; else return x;}

Page 15: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 15

Parameters vs. Arguments

Parameters are variables that are listed in the function’s parameter list int max(int m, n)

Arguments are variables that are listed in the function’s callsint main(){

int m = 2, n = 3;int max_number = max(m, n);

}

Page 16: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 16

Local Variables & Functions

A local variable is simply a variable that is declared inside a block and can then be accessed only from within that block

Since the body of a function itself is a block, variables declared within a function are local variables to that function; they exist only while the function is executing

Are function’s formal parameters regarded as being local to the function?

Page 17: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 17

Sample Local Variableslong fact(int n) {

if (n < 0) return 0;int f = 1;while (n > 1)

f*= n--;return f;

}int main() {

long f = fact(2);} Which variables are local variables in function

‘fact’?

Page 18: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 18

Void Function A function does not need to return a value In C++, such a function is identified

simply by placing the keyword void where the function’s return type would be

It does not need to include a return statement. If it does have a return statement, then it should appear simply as return;

Do we need to do ‘return;’ at the end of the function?

Page 19: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 19

Sample Function with Void

void printMonth(int);int main() { printMonth(1); }void printMonth(int m) {

if (m < 1 || m > 12)cerr << “Error”; return;

switch (m) {

case 1: cout << “January”; break; …

}}

Page 20: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 20

Boolean Functions In some situations, it is helpful to use a

function to evaluate a condition, typically within an if or a while statement

bool isLeapYear(int y) {return (y%4 == 0 && y%100 != 0 ||

y%400 == 0); }int main(){

if (isLeapYear(2004))cout << “2004 is a leap year\n”;

}

Page 21: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 21

I/O Functions We have already seen examples of

output functions that send information to the standard output

The next example illustrates an input example

How to write a function that prompts the user for his/her age and that keeps asking for the number until it is the range of 0 to 120?

Page 22: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 22

Robust I/O Functionint age(){int n; while (true) {

cout << “How old are you:”;cin >> n;if (n < 0) cout << “Your age could not be negative\n”;else if (n > 120) cout << “Your age could not be over 120\n”;else return n;}}

int main() { cout << “You are “ << age() << “ years old” << endl;}

Page 23: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 23

Passing by Value vs. by Reference

Pass-by-value (value parameters) The values of variables are passed. The

values of variables are read-only; they do not change when they are referred outside the function

Pass-by-reference (reference parameters) The addresses of variables are passed. The

values of variables are read-write; they can be modified and this modification is still in effect even at outside the function

Page 24: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 24

Sample Pass by Value vs. by Reference

void swap(float x, float y) {float temp =x; x = y; y = temp; }

int main() {

float a = 22.2, b = 44.4;cout << “a = “ << a << “ b = “ << b << endl;swap(a, b);cout << “a = “ << a << “ b = “ << b << endl;

} What is the output?

Page 25: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 25

Sample Pass by Value vs. by Reference

void swap(float &x, float &y) {float temp =x; x = y; y = temp; }

int main() {

float a = 22.2, b = 44.4;cout << “a = “ << a << “ b = “ << b << endl;swap(a, b);cout << “a = “ << a << “ b = “ << b << endl;

} What is the output?

Page 26: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 26

Sample Pass by Value vs. by Reference

void f(int x, int &y) { x = 88; y = 99;}int main() { int a = 22, b = 44;

cout << “a = “ << a << “, b = “ << b << endl;f(a,b); cout << “a = “ << a << “, b = “ << b << endl;f(2*a-3, b); cout << “a = “ << a << “, b = “ << b << endl;}

What is the output?

Page 27: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 27

Pass by Value vs. by Reference

Passing by Value Passing by Reference

int x; int &x;

x is a local variable x is a local reference

x is a duplicate of the argument

x is a synonym for the argument

Argument cannot change

Argument can change

Arg can be a constant, a variable, an expression

Argument is a variable

Argument is read-only Argument is read-write

Page 28: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 28

When to Pass by Reference?

Besides when we want to change the variables after the function returns to the calling function

How to return more than one value from the function?

How to write a function that accepts a radius of a circle and returns the area and the circumference of a circle whose radius ahs the given length r?

Page 29: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 29

Sample Pass by Reference

void computeCircle(double &area, double &circumference, double r) {

const double PI = 3.14159265358979;area = PI*r*r;circumference = 2*PI*r;

}int main() {

double r, a, c; cout << “Enter radius: “;cin >> r; computeCircle(a, c, r);cout << “ area = “ << a << “ circumference = “ << c << endl;

}

Page 30: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 30

Passing by Constant Reference

If you don’t want the function to change its content (for example, if the purpose of the function is to print the object), then passing by reference can be risky

Passing by constant reference works the same way as passing by reference, except that the function is prevented from changing the value of the parameter

In which case, we prefer to pass by constant reference over pass by value?

Page 31: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 31

Sample Pass by Value vs. by Reference

void f(int x, int &y, const int &z) { x+= z; y += z; cout << “x = “ << x << “, y = “ << y << “, z = “

<< z << endl;}int main() {

int a = 22, b = 33, c = 44;cout << “a = “ << a << “, b = “ << b << “, c = “ << c << endl;f(a,b,c);cout << “a = “ << a << “, b = “ << b << “, c = “ << c << endl;

f(2/a-3,b,c);cout << “a = “ << a << “, b = “ << b << “, c = “ << c << endl;

}

Page 32: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 32

Inline Functions Do we always want to call a function? A function call involves substantial

overhead. Extra time and space have to be used to

invoke the function, pass parameters to it, allocate storage for its local variables, store the current variables and the location of execution in the main program

In some cases, it is better to avoid all of this by specifying the function to be inline

Page 33: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 33

Inline Functions (Cont.) Inline functions tell the compiler to

replace each call to the function with explicit code for the function

To the programmer, an inline function appears the same as an ordinary function, except for the use of the inline function

Page 34: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 34

Sample Inlining Function inline int cube(int x) { return x*x*x;}int main() {

cout << cube(4) << endl;int x, y;cin >> x;y = cube(2*x – 3);

}cout << cube(4) … cout << 4*4*4 …y = cube(2*x-3) y = (2*x-3)*(2*x-3)*(2*x-

3);

Page 35: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 35

Scope The scope of a name consists of that

part of the program where it can be used

It beings where the name is declared If that declaration is inside a function

then the scope extends to the end of the innermost block contains the declaration

A program can have several objects with the same name if their scopes are nested or disjoint

Page 36: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 36

Sample Scopes int x = 11; // global variable x int main() {

int x = 22; { int x = 33;cout << “In block1 x = “ << x << endl;}

{int x = 44;cout << “In block2 x = “ << x << endl;}

cout << “x = “ << x << “ ::x = “ << ::x << endl;}

What is the output?

Page 37: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 37

Sample Scopes and Functions

int x = 11;void f() { int x = 44; cout << “In f(): x = “ <<

x << endl;}void g() {cout << “In g(): x = “ << x <<

endl;}int main(){

int x = 22; cout << “In main x = “ << x << endl;f(); g();

} What is the output?

Page 38: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 38

Overloading C++ allows you to use the same

function name for different functions as long as they have different parameter type lists

Two parameter lists are different if They contain a different number of

parameter Or there must be at least one position in

their parameter lists where the types are different

Page 39: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 39

Sample Overloading Program

#include <iostream>using namespace std;int max(int, int);int max(int, int, int);int main() {

cout << max(99,77) << " " << max(55, 66, 33);}int max(int x, int y) {

return (x > y? x: y);}int max(int x, int y, int z) {

int m = (x > y ? x: y);return (z > m? z:m);

}

Page 40: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 40

The main Function A Complete C++ program is a

program made up of the main() function together with all other functions that are called either directly or indirectly from it

main() is a function with return type int, it is normal to end its block with

return 0;int main(){ return 0;}

Page 41: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 41

Using ‘return’ to Terminate a

Program If ‘return’ is called in a main function, it is

used to terminate a programint main() {

int n, d;cout << “Enter two integers:”;cin >> n >> d;if (d == 0) return 0;cout << n << “/” << d << “ = “ << n/d << endl;

}What are the outputs when n=99, d = 17

and when n = 99, d = 0?

Page 42: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 42

Terminating a Program Abnormally

There are many ways to terminate a program abnormally, such as Use a return statement in main()

Example: int main() { return 1; } Call the exit() function

Example: int main() {exit(1); } Call the abort() function

Example: int main() { abort(); }

Page 43: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 43

Default Arguments In C++, the number of arguments that

a function has can vary during run-time This is done by providing default

values for the optional arguments All default argument names of a

function are bound when the function is declared

All functions have their types checked at declaration, and are evaluated at each point of call

Page 44: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 44

Evaluating C++ Default

Arguments When a function defined with default

arguments is called with trailing arguments missing, the default expressions are evaluated

void f(int a, int b = 2, int c = 3); // declaration

f(a); // same as call f(a, 2, 3) f(a,10); // same as call f(a,10,3) f(a,10,20); // no default arguments

Page 45: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 45

Sample Default Arguments

double p(double x, double a0, double a1 = 0, double a2 = 0) {return a0 + (a1 + a2*x)*x;}

int main(){ double x = 2;

cout << “p(x,2) = “ << p(x,2) << endl;cout << “p(x,2,3) = “ << p(x,2,3) << endl;cout << “p(x,2,3,4) = “ << p(x,2,3,4) << endl;}

What is the output?

Page 46: Chapter 9 Functions Dept of Computer Engineering Khon Kaen University.

178110: Computer Programming (II/2546) 46

Reviews What are functions? Why do need them? What are the header and the body parts

of functions? Function declaration vs. function

definition Parameters vs. arguments Passed by values vs. pass by references Terminating functions and programs Default arguments