Вы находитесь на странице: 1из 34

Function

OBJECTIVES
To be able to implement functions

To become familiar with the concept of parameter

passing To develop strategies for decomposing complex tasks into simpler ones To be able to determine the scope of a variable To recognize when to use value and reference parameters

Introduction to Function

Divide and conquer Construct a program from smaller pieces or components Each piece more manageable than the original program

More about Function

Functions are invoked by a function call A function call specifies the function name and provides information (as arguments) that the called function needs Boss to worker analogy:

A boss (the calling function or caller) asks a worker (the called function) to perform a task and return (i.e. report back) the results when the task is done.

Types of Function
Predefined Function: The use of C++ standard

library function - pow(2,3) cos(4.0)


User-defined Function: Programmers create

function to organize/divide tasks in a program

Predefined Functions
Function Header File Purpose
Parameter Type

Result

abs(x)

<cstdlib> Returns absolute value of


its argument: abs(-7)=7

int
double

int
double

fabs(x)

<cmath>

Returns the absolute value of its argument: Fabs(-5.67)=5.67 value of x if x is uppercase; otherwise returns x

tolower(x) <cctype> Returns the lowercase

int

int

toupper(x) <cctype> Returns the uppercase


value of x if x is lowercase; otherwise returns x

int

int

Example 6-1 sample run:

User-Defined Functions
1.Value-returning functions: have a return type
Return a value of a specific data type using the return statement

2.Void functions: do not have a return type


Do not use a return statement to return a value

1. 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

1. Value-Returning Functions
(To use for?..) Because the value returned by a valuereturning function is unique, we must:
Save the value for further calculation Use the value in some calculation Print the value

A value-returning function is used in an assignment or in an output statement

1. Value-Returning Functions
(definition)
Format for function definition:

Function header

Return-value-type Function-name ( Parameter-list ) { variable declarations Braces Function body . return expression } parameter-list for a function
Example:

declaration takes the form of: type var_1, type var_2,

float square( int y, float z) { return y * z; }

1. Value-Returning Functions
1

(example) int add(int b, int c);

int add(int b, int c); int main(){ int a = add(3,4); cout << a; return 0; }
Return value

Passing arguments

int main(){ cout << add(3,4); return 0; } int add(int b, int c){ return b+c; }

int add(int b, int c){ return b+c; }

1. Value-Returning Functions
3

(example) int add(int b, int c);

int add(int b, int c); int main(){ int b=3, c=4; cout << add(b,c); return 0; } int add(int b, int c){ return b+c; }

int main(){ cout << add(3,4); return 0; } int add(int b, int c){ int m = b+c; return m; }

1. Value-Returning Functions
5

(example)

int add(int b, int c){ return b+c; }

int add(int , int, float); int main(){ cout << add(3,4,1.0); return 0; } int add(int b, int c, float d){ int m = b+c-d; return m; }

int main(){ int b=3, c=4; cout << add(b,c); return 0; }

return Statement
Once a value-returning function computes the value, the function returns this value via the return statement
It passes this value outside the function via the return statement

Exercise
Write a program using value returning function (with two parameter) that reads two number and display the biggest number.

#include <iostream> using namespace std; int max (int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } int main ( ) { int i = 5; int j = 2; int k = max (i, j); cout << The Biggest Number : << k; return 0; }

2. Void Functions
void box_string(string str)

Use a return type of void to indicate that a function does not return a value. void functions are used to simply do a sequence of instructions They do not return a value to the caller.

2. Void Functions (example)


#include <iostream> using namespace std; void prt (int); int main ( ) { int X = 12; prt ( X ); return 0; }
Passing arguments

//Function prototype

//Defines the integer variable //Calls prt ( ) and passes it X // Returns 0 to the environment

void prt (int Y) { cout << Y ; return; }

//The prt ( ) function definition //Displays the value of Y //Returns no value, passes //control to main ( )

2. Void Functions (example)


1 2

void add(int, int, float);

void add(int b, int c){ int tot = b+c; cout << tot; }
int main(){ int b=3, c=4; add(b, c); return 0; }

int main(){ add(3, 1, 2.3); return 0; } void add(int b, int c, float d){ cout << b+c-d; }

Exercise
Write a program using void function (with one parameter) that reads one score mark and display the grade.

#include <iostream> using namespace std;

void printGrade (double score) { if (score >= 90.0) cout << A; else if (score >= 80.0) cout << B; else if (score >= 70.0) cout << C; else if (score >= 60.0) cout << D; else cout << F; }

int main ( ) { double score; cout << Enter a score : ; cin >> score;

cout << The grade is : ; printGrade(score);


return 0; }

Parameters: Reference & Values


Call by value

Copy of data passed to function Changes to copy do not change original Used to prevent unwanted side effects Call by reference Function can directly access data Changes affect original

Passing by reference
Reference parameter for argument
& is used to signify a reference void change( int &variable ) { variable += 3; }

- Is like passing the address of variable used as argument in function call. - (Example next slide)

void swap(int &px, int &py) // pass by reference { int temp; temp = px; px = py; py = temp; }
int main() { int a = 10, b = 20; swap(a,b);
cout << "Value of a is " << a <<endl; cout << "Value of b is " << b << endl; return 0;

#include <iostream> using namespace std;

PASS ARGUMENTS BY VALUE

void increment (int n) { n++; cout << n inside the function is << n << endl; } int main ( ) { int x = 1; cout << Before the call, x is << x << endl; increment (x); cout << After the call, x is << x << endl; return 0; }

Output: Before the call, x is 1 n inside the function is 2 After the call, x is 1

The value of x (1) passed to the parameter n to invoke the increment function. n is incremented by 1 in the function but x is not changed no matter what the function does

#include <iostream> PASS ARGUMENTS BY REFERENCES using namespace std; void increment (int &n) { n++; cout << The address of n is << &n << endl; cout << n inside the function is << n << endl; }

int main ( ) { int x = 1; cout << The address of x is << &x << endl; cout << Before the call, x is << x << endl; increment (x); cout << After the call, x is << x << endl; return 0; }

Output: The address of x is 0013FF60 Before the call, x is 1 The address of n is 0013FF60 n inside the function is 2 After the call, x is 2

Invoking increment(x) passes the reference of variable x to the parameter &n in the increment function. Now n and x have the same address 0013ff60, as shown in the output. Incrementing n in the function is the same as incrementing x. So before the function is invoked, x is 1, and afterward x becomes 2.

Pass by value
void swap(int px, int py) //pass by value { int temp; temp = px; px = py; py = temp; }
int main() { int a = 10, b = 20; swap(a,b); cout << "Value of a is " << a <<endl; cout << "Value of b is " << b << endl; getch(); return 0; }

Summary
Understand the philosophy of Functions Functions Constructs Function Definitions
Function Header (Return-value-type, Function-name, Parameterlist) Function Body

Function Prototypes Function Calls

Pass-by-value VS. Pass-by-reference

int secret(int x){ int i, j; i = 2 * x; if (i > 10) j = x / 2; else j = x / 3; return j 1; }

Q:

int another(int a, int b){ int i, j; j = 0; for(i=a; i<=b; i++) j = j + i; return j ; }

Assume x, y, k are int. What is the output? a. x = 10; cout << secret(x) << endl; b. x = 5; y = 8; cout << another(x, y) << endl;

Вам также может понравиться