chap6

26
Function and pointer Hung Vo Ho Chi Minh City University of Technology [email protected] 2015 Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 1 / 26

Upload: tran-anh-tan

Post on 12-Dec-2015

4 views

Category:

Documents


0 download

TRANSCRIPT

Function and pointer

Hung Vo

Ho Chi Minh City University of Technology

[email protected]

2015

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 1 / 26

Overview

1 Function

2 Pointer

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 2 / 26

Function: declaration

User-defined program units are called subprograms

In C++ all subprograms are referred to as functions.

A function consists of a set of statements that have been collectedtogether and given a name

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 3 / 26

Function: declaration (cont.)

result-type name(parameter-list) {

. . . body . . .

}

result-type is the type of value returned by the function

name is the function name

parameter-list is a list of declarations separated by commas, givingthe type and name of each parameter

The body of the function is a block and typically containsdeclarations for the local variables required

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 4 / 26

Function: declaration (cont.)

Example:

void findMax(int x, int y){

int maxnum;

if ( x >= y)

maxnum = x;

else

maxnum = y;

cout << "\n The maximum of the two numbers is " << maxnum

<< endl;

return;

}

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 5 / 26

Function: returning values

As they return, functions can send results back to the calling program

Syntax:return value;

orreturn (value);

Special case: return;

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 6 / 26

Function: prototype

Before using a function, you declare it by specifying its prototype

A prototype has exactly the same form as a function definition,except that the entire body is replaced by a semicolon. The names ofthe parameter variables are optional in a prototype, but supplyingthem usually helps the reader

Example:

void findMax(int, int);

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 7 / 26

Function: how to call

The act of using the name to invoke the associated statements isknown as calling that function

You designate a data type for function since it will return a valuefrom a function after it executes

Variable names that will be used in the function header line are calledformal parameters

To execute a function, you must invoke, or call, it from the main()function (or ...)

The values or variables that you place within the parentheses of afunction call statement are called actual parameters

findMax(a, b);

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 8 / 26

Function: example

// Finding the maximum of three integers

#include <iostream.h>

int maximum(int, int, int); // function prototype

int main()

{

int a, b, c;

cout << "Enter three integers: ";

cin >> a >> b >> c;

cout << "Maximum is: " << maximum (a, b, c) << endl;

return 0;

}

// Function maximum definition

// x, y and z are parameters to the maximum function definition

int maximum( int x, int y, int z)

{

int max = x;

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 9 / 26

Function: example (cont.)

if ( y > max )

max = y;

if ( z > max )

max = z;

return max;

}

The output of the above program:Enter three integers: 22 85 17Maximum is: 85

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 10 / 26

Function: pass by value and reference

Pass by value

If a variable is one of the actual parameters in a function call, thecalled function receives a copy of the values stored in the variable.

After the values are passed to the called function, control istransferred to the called function.

Example: The statement findMax(firstnum, secnum); calls thefunction findMax() and causes the values currently residing in thevariables firstnum and secnum to be passed to findMax().

The method of passing values to a called function is called pass byvalue.

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 11 / 26

Function: pass by value and reference (cont.)

With call-by-reference, the caller gives the called function the abilityto access the caller”s data directly, and to modify that data if thecalled function chooses so

To indicate that the function parameter is passed-by-reference, simplyfollow the parameter”s type in the function prototype of functionheader by an ampersand (&)

For example, the declarationint& count

in the function header means ”count is a reference parameter to anint”

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 12 / 26

Function: pass arrays to functions

To pass an array to a function, specify the name of the array withoutany bracketsint hourlyTemperature[24];

modifyArray(hourlyTemperature, size);

For the function to receive an array through a function call, thefunction”s parameter list must specify that an array will be receivedvoid modifyArray(int b[], int arraySize)

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 13 / 26

Function: pass arrays to functions (cont.)

#include<iostream>

using namespace std;

int linearSearch( int [], int, int);

int main()

{

const int arraySize = 100;

int a[arraySize], searchkey, element;

for (int x = 0; x < arraySize, x++) // create some data

a[x] = 2*x;

cout<< "Enter integer search key: " << endl;

cin >> searchKey;

element = linearSearch(a, searchKey, arraySize);

if(element !=-1)

cout<<"Found value in element "<< element << endl;

else

cout<< "Value not found " << endl;

return 0;

}

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 14 / 26

Function: pass arrays to functions (cont.)

int linearSearch(int array[], int key, int sizeofArray)

{

for(int n = 0; n< sizeofArray; n++)

if (array[n] = = key)

return n;

return 1 ;

}

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 15 / 26

Function: inline function

For small functions, you can use the inline keyword to request that thecompiler replace calls to a function with the function definition whereverthe function is called in a program

// Using an inline function to calculate the volume of a cube.

#include <iostream>

using namespace std;

inline double cube(double s) { return s * s * s; }

int main()

{

cout << "Enter the side length of your cube: ";

double side;

cin >> side;

cout << "Volume of cube with side "

<< side << " is " << cube(side) << endl;

return 0;

}

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 16 / 26

Function: Overloading

C++ enables several functions of the same name to be defined, aslong as these functions have different sets of parameters (at leasttheir types are different).

This capability is called function overloading.

When an overloaded function is called, C++ compiler selects theproper functions by examining the number, types and order of thearguments in the call.

Function overloading is commonly used to create several functions ofthe same name that perform similar tasks but on different data types.

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 17 / 26

Function: Overloading (cont.)

void showabs(int x)

{

if( x < 0)

x = -x;

cout << The absolute value of the integer is << x << endl;

}

void showabs(double x)

{

if( x < 0)

x = -x;

cout << The absolute value of the double is << x << endl;

}

The function call showabs(10); causes the compiler to use the 1st versionof the function showabs.

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 18 / 26

Function: Default arguments

C++ allows default arguments in a function call.

Default argument values are listed in the function prototype and areautomatically passed to the called function when the correspondingarguments are omitted from the function call.

Example: The function prototypevoid example (int, int = 5, float = 6.78);

provides default values for the two last arguments.

If any of these arguments are omitted when the function is actuallycalled, C++ compiler supplies these default values.

example(7,2,9.3); // no default used

example(7,2); // same as example(7, 2, 6.78)

example(7); // same as example(7, 5, 6.78)

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 19 / 26

Function: recursion

How the Computation is Performed

The mechanism that makes it possible for a C++ function to callitself is that C++ allocates new memory locations for all functionparameters and local variables as each function is called.

There is a dynamic data area for each execution of a function. Thisallocation is made dynamically, as a program is executed, in amemory area referred as the stack.

A memory stack is an area of memory used for rapidly storing andretrieving data areas for active functions. Each function call reservesmemory locations on the stack for its parameters, its local variables, areturn value, and the address where execution is to resume in thecalling program when the function has completed execution (returnaddress).

Inserting and removing items from a stack are based onlastin/first-out mechanism.

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 20 / 26

Function: recursion (cont.)

unsigned long factorial( unsigned long );

int main()

{

for ( int i = 0; i <= 10; i++ )

cout << setw( 2 ) << i << "! = " << factorial( i ) << endl;

return 0;

}

unsigned long factorial( unsigned long number )

{

if (number < 1) // base case

return 1;

else // recursive case

return number * factorial( number - 1 );

}

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 21 / 26

Function: recursion (cont.)

A data area for the execution of this function call is pushed on top ofthe stack

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 22 / 26

Function: recursion (cont.)

Progress of execution when call factorial with number = 3

factorial(0)

factorial(1) factorial(1) factorial(1)

factorial(2) factorial(2) factorial(2) factorial(2) factorial(2)

factorial(3) factorial(3) factorial(3) factorial(3) factorial(3) factorial(3) factorial(3)

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 23 / 26

Pointer

A pointer is a special type of variable that stores the memory addressof other variables

int *pFirstPtr;

int *pSecondPtr;

You use the address-of operator (&) to assign to the pointer variablethe memory address of another variable

int x;

pFirstPtr = &x;

If ptr is a pointer variable, *ptr means the contents of the variablepointed to by ptr

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 24 / 26

Pointer: example

#include<iostream>

using namespace std;

int main()

{

int a;

int *aPtr; // aPtr is a pointer to an integer

a = 7;

aPtr = &a; //aPtr set to address of a

cout << The address of a is << &a

<< \nThe value of aPtr is << aPtr;

cout << \n\nThe value of a is << a

<< \nThe value of *aPtr is << *aPtr

<< endl;

return 0;

}

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 25 / 26

The End

Hung Vo (CSE) Programming Fundamentals (CO1011) 2015 26 / 26