1 section 3 c++ pointer and functions. 2 l-value and r-value l-value and r-value two types of values...

70
1 SECTION 3 C++ Pointer and Functions

Post on 20-Dec-2015

231 views

Category:

Documents


0 download

TRANSCRIPT

1

SECTION 3

C++ Pointer and Functions

2

L-value and R-value

L-Value and R-ValueTwo types of values are associated with

a variable.– l-value : the address value of the

variable.– r-value : the real value of the variable.The left hand side of an assignment

operatorrequires an l-value.

3

L-value and R-value

Example:int x = 10,y = 20;x = y; // r-value of y is stored in the l-value of x;y = x; // r-value of x is stored in the l-value of y;x = 1; // r-value of literal constant 1 is stored in

the// l-value of x1 = y; // error. no l-value for literal constant 1.++ x; // x=x+1++ 10; // ?

4

Pointer definition

Syntax:base type * pointer name;where base type defines the type of

variable thepointer points to.Example:int * ptr1; // a pointer to integer.int * * ptr2; // a pointer to pointer to integerint * ptr1, ptr2; // a pointer and an integer

5

Figure of Memory Allocation

dynamic objects memory managed by

programmer;by explicitly

call of new/deleteFunction parameters, Local objects memory managed by

compiler; used for each function call global objects global data:object locations are fixed value but can

be changed

Function definitions code and read-only objects

6

Memory AllocationIn C++, operator new and delete are used to allocate and free

storage dynamically.

int main(){int *ptr1;float *ptr2;ptr1 = new int;// In C: ptr1=malloc (sizeof(int));ptr2 = new float;// In C: ptr2=malloc (sizeof(float));*ptr1 = 20;*ptr2 =13.5;delete ptr1;// In C: free(ptr1);delete ptr2;

}

7

Memory Allocation

8

Dynamic Arrays

Example :int main(){

float *a;int n;cout << ``enter size of list:'';cin >> n;a = new float[ n ];// C code: a = malloc(n * sizeof(float));for(int i=0; i<n; i++)

cin >> a[i];delete [] a;

}

9

Dynamic Arrays

Use delete [] when the dynamic object is an array.

10

Dynamic Allocation ofMulti-dimensional Array

Example:#include <iostream>using namespace std;int main(){int m,ncout << ``enter the number of rows and columns: ''<<'\n';cin >> m >> n;int **a; //a is a pointer to pointer to integera = new int*[m]; //a points to an array of integer pointer //the size of this pointer array is m

11

Dynamic Allocation ofMulti-dimensional Array

for(int i=0; i<m; i++) //each pointer in the array points toa[i] = new int[n]; //an array of integer

//the size of these integer arrays is ncout <<''Enter values for this ''<<m<<''by''<<n<<''array:\n'';for(int i=0; i<m; i++)

for(int j=0; j<n; j++)cin >> a[i][j];

for (int i=0; i<m; i++) //deallocate memorydelete [] a[i];

delete [] a;}

12

Dynamic Allocation ofMulti-dimensional Array

13

Dynamic Allocation of Multi-dimensional Array

14

Dynamic Allocation of Multi-dimensional Array

Note:

•In C++, new, new[], delete, delete[] are built-in operators

rather than library functions.

•new, new[], delete, delete[] should be used together, and not mixed with C storage management functions (malloc, free).

•Programmer should explicitly deallocate the memory of

dynamic objects.

15

Dynamic Allocation of Multi-dimensional Array

Related problems:

– memory leak– dangling pointer

16

Dynamic Memory Allocation

Questions:

Does the statementdelete ptr;delete the pointer ptr or the object

being referred by ptr?

17

C++ Reference Type

In C++, reference type provides an alternative name for an object. The definition of a reference is preceded by the & operator.

Example:int x = 10;int &ref1 = x; // ref1 is a reference to int x.int *& ref2 = ptr // ref2 is a reference to int

pointer ptr.A reference is a name alias - Not a

pointer !

18

C++ Reference Type

The main use of reference is for specifying arguments and return values for functions in general and for overloaded operators in particular.

When a reference is defined, it must be initialized to an object.

Once initialized, a reference can not be reassigned to refer to another object.

19

C++ Reference Type

Example: //sam7.cppint a, b=5;int &ref = a; // a and ref both refer to same memory

location! // ref is an alias for aa = 3;ref = 3; // both affect aref = b; //ref=5ref++; //ref=6//Compared to pointer:int *ptr; // ptr is a new objectptr = &a;*ptr = 3;ptr = &b; // ok

20

C++ Reference Type

Reference types are usually used as functionparameters. It can

– increase code clarity,– reduce function parameter costs,– optimize compilation.

21

C++ Reference Type

A reference is just an alias, it’s different from pointer.

Some differences between a reference and a pointer: • A reference cannot be NULL • Once established a reference cannot be changed • An alias does not need dereferencing • A reference is declared by using the ampersand • All operators operate on the actual value not

reference

22

C++ Reference Type

The most common use of reference is pass by reference to a function (allowing the function to change the actual value)

Example:#include <iostream> void passExample ( int & i ) { i++; i = i + 1; } int main () { int j = 5; passExample(j); cout << j << endl; return 0; }

23

Functions in C++

A function declaration ( function prototype ) consists of the function name, its return type, and the number and types of the function parameters.

Example:

int f(int, int); // declaration of f:// f has two integer parameters// and returns a integervoid g(); // declaration of g:// g has no argument and returns nothing

24

Functions in C++

• A function body or function block is the function implementation enclosed in braces.

• A function definition is composed of the function declaration and the function body.

• Actual parameters: arguments provided at the function call; they are placed inside the call operator.

• Formal parameters: parameters received by the function definition.

• A function is evaluated when the function name is followed by the call operator ( ).

25

Functions in C++

Note:C++ is a strongly typed language. A function

cannot be called unless it is previously declared.

The following two prototypes of main are supported by all C++ compilers.

int main(){}int main(int argc, char *argv[]){}

26

Parameter Type CheckingThe arguments of every function call are type-checked during

compilation. If there is a type mismatch, implicit conversion is applied if possible.

//sam8.cppvoid f( int ){ /* ... */ }int x = 0;bool flag = true;char c = 'a';f( 10 ); // exact matchf( x ); // exact matchf( flag ); // match with a promotionf( c ); // match with a promotionf( 12.34 ); // match with a standard

conversionf( "hello" ); // mismatchf( 12, 3 ); // mismatch

27

Call by ValueThe default argument passing method in C++ is call by

value.

Example:void f(int x);int main(){

int a = 10;f(a);f(10);

}void f(int x){

x += 100;}

28

Call by Value

During the first function call to f()

• a is the actual parameter; x is the formal parameter

• Because a is passed by value, its content is copied to the function’s parameter x

• x and a are physically two different memory cells

29

Call by Value

30

Call by Value

31

Call by Reference

Call by reference can be simulated by using pointer and address passing.

Example:void swap(int *a, int *b);int main(){

int x = 1;int y = 2;swap(&x, &y);

}

32

Call by Reference

void swap( int *a, int *b){int tmp;tmp = *a;*a = *b;*b = tmp;

}

33

Call by Reference

The reference operator is usually used to specify a call-by-reference parameter in C++.

Example 1: //sam9.cppvoid f(int a, int &b);int main(){

int i = 0;int j = 0;f(i, j);cout << i <<'\n'; //i=0cout << j <<'\n'; //j=1

}void f(int a, int &b){

a++;b++;

}

34

Call by Reference

Example 2:void swap(int &a, int &b);int main(){

int x = 1;int y = 2;swap(x, y);

}void swap(int &a, int &b){

int tmp;tmp = a; // not tmp = *a !a = b;b = tmp;

}

35

Call by Reference

36

Return by ValueWhen a function returns an object by value, the

value to be returned is copied to a temporary storage before the function call ends, so the calling function can access the value.

Example:int f(int x){x = x*x - 100return x;}int main(){

int y = f(10);}

37

Return by Value

38

Return by Reference

When a function returns an object by reference

using reference operator (&), the object is returned

as l-value.Example: //sam10.cppint& f( int *ptr, int x ){

return ptr[x];}int main(){

int a[100];cout<<f( a, 10 )<<endl;

}

39

Return by Reference

A local object should not be returned by reference since the lifetime of local object ends when the function call finishes.

Example:int& add(int x, int y){

int result = x + y;return result; // error

}

40

Array ParametersWhen an array is used as a function argument, the address

of the array is passed.Example: //sam11.cppvoid display(int num[10], int size);int main(){

int a[10];for(int i=0; i<size; i++)a[i] = i;display(a, 10);

}void display(int num[10], int size){

for (int i=0; i<size; i++)cout<< num[i] <<'\n';

}

41

Array Parameters

Three equivalent declarations of display

void display(int num[10], int size);void display(int num[], int size);void display(int *num, int size);

The function call display(a, 10) is an exact match of any of the above declarations.

42

Array Parameters

To avoid modifying the local copy of array elements, we can use the const specifier.

void display(const int *num, int size){// ...}

43

Array Parameters

Since an array is passed as a pointer, the size of the array is not known in the function called.

Example:void display( int num[10] );int main(){int i, j[2];display( &i ); // ok: &i is type int*display( j ); // j is type int* // but, potential run-time

error}

44

Default ArgumentIn C++, default values can be specified for

function parameters, so the function can be called without being provided all the arguments.

Example:void f( int x, double m=12.34 );int main(){f( 1, 1234.56 ); // okf( 1 ); // ok, m=12.34f(); // error! no default value for x}

45

Default Argument

Default arguments can be provided by trailing arguments only.

void f( int x=1, double m, char s='a'); // wrongvoid f( int x=1, double m=12.34, char s); //

wrongvoid f( int x, double m, char s='a'); // ok

46

Default ArgumentDefault arguments should be supplied in a

function declaration, not in a function definition.

Example:// file f.hvoid f(int, int);

// file f.cppvoid f( int a = 2, int b = 3){// ...}

47

Default Argument

Correct version:

// file f.hvoid f(int a = 2, int b = 3); // also ok: void f(int = 2 , int = 3);// file f.cppvoid f( int a, int b){//...}

48

Default Argument

For a previously defined function, additional default arguments can be specified using succeeding declarations. Thus, a general function can be customized for a more specific use.

Example:The UNIX system library function chmod()

changes the protection level of a file. It is declared as:

int chmod( char *filePath, int protMode );

49

Default Argument

chmod() can be redeclared to supply the protection mode value a default value of read-only.

#include <cstdlib>int chmod( char *filePath, int protMode = 0444 );

50

Scope and LifetimeTwo questions:

How long does the object exist lifetime

The life time of a C++ object is either static, automatic, or dynamic. This is referred to as the storage class of an object.

Where the object can be used scope

C++ supports local scope, namespace scope and class scope.

51

Object Lifetime

Dynamic object objects live until it is destroyed by programmer using "delete" function parameters, object live until the end

Local objects of function call or local scope

Global objects object live for the entire execution of program

Function definitions objects (literal constant) live for the entire execution of program

52

Local Scope and Local Objects

• A local scope is the program text enclosed inbraces {}. Each function block represents adistinct local scope.

• An object declared in local scope is a local objectto the block.

• A local object can be – Automatic object

– Static local object

53

Local Scope and Local ObjectsAn automatic object has its storage allocated when

the block is entered, and its storage deallocated when the block ends.

Example:void f(int, int);int main(){ // in scope of main

int x = 1, y = 2;f( x, y );{

int x; // nested scopes}

}void f(int a, int b){ // in scope of f()

int tmp;tmp = a + b;

}

54

Static Local Objects

A local object with static specifier. Static objects persist for the entire duration of the program.

55

Static Local Objects

Example: void f();int main(){f(); f(); f();}void f(){

static int i; // initialized to 0 by defaultint x = 0;cout <<''i = '' << i <<''x = '' << x <<'\n';i = i+1;x = x+1;

}What is the output?

56

Static Local Objects

Note:The word static has double meaning

in C++:1. regarding memory allocation.2. regarding scope of variable.

57

Dynamically Allocated ObjectsA dynamically allocated object is created by the

programmer using a new expression, and terminated by user with a delete.

Example:int* f(){

int *ptr = new int;return ptr;

}int main(){

int *ptr;ptr = f();delete ptr;

// ... }

58

Function Overloading

• In C++, functions can be overloaded if they have

the same name, declared in the same scope andhave different signatures.

• The signature of a function consists of thenumber, data types and order of the function’s parameter list.

• Function overloading is a form of polymorphism.

59

Function Overloading

Functions must have distinct signatures to be

overloaded.Example:void f1(int);void f1(double);

void f2(int);void f2(int, int);

void f3(int, double);void f3(double, int);

60

Function Overloading

Functions must have distinct signatures to be overloaded.

Example:void f4(int, double); // ok?int f4(int, double);

void f5( char* ); // ok?void f5( char[] );

void f6( int ); // ok?void f6( const int );

61

Function Overloading Resolution

A function call is associated with one function in a set of overloaded functions through the process of function overload resolution.

62

Function Overloading Resolution

The 3 steps of overloaded function resolution.1. Find candidate functions: functions that

match the name.2. Find viable functions: functions that can be

called from the candidate function list.3. Find the best viable function: the best match,

if the exact match is not available.

If no best match found, then the function call isambiguous.

63

Function Overloading Resolution

Exercise: Which f()will be called?void f();void f( int );void f( double, double = 12.34 );void f( char*, char* );int main(){f( 56.78 );}

64

Inline Function

In many programming languages, programmers

have to choice between• Abstraction/modularity( function call )• Performance( macro or inline-expansion by

hand )

Functions: good abstraction but introduce overhead at run-time.

C macro: efficient but problematic.

65

Inline Function

Example:

#define SQUARE(X) ( (X) * (X) )int a = SQUARE(10); // expanded by

preprocessor to // int a = 10 * 10;int x = SQUARE(a++); // problem here

expanded to // int x = (a++) * (a+

+)

66

Inline Function

An inline function is a function that is expanded

at the point of the function call at compilation time rather than actually being executed at run-time.

Consider the function max():inline int max( int x, int y ){

return( x > y ? x : y );}

67

Inline Function

so the code:int Max = max( a, b );may be expanded during compilation as:int Max = ( a > b ? a : b );Using inline functions avoids the

overhead offunction calls, while preserves the

benefits ofabstraction.

68

Pointer to Functions

In C/C++, pointers to function can be declared

to store the address of a function.double f1(double x );double f2(double x );int f3();double (*fptr)(double); // fptr is a pointer to function which // takes a double and returns a

doublefptr = f1; // okfptr = &f2; // okfptr = f3; // wrongresult = (*fptr)( 12.34 ); // okresult = fptr( 12.34); // ok

69

Functions as Arguments

Functions can be passed as arguments into another function through function pointers.

Example:#include <iostream>using namespace std;void plot(double (*fptr)(double), double, double, int);double f1(double x );double f2(double x );int main(){

cout << "Mapping first function" << endl;plot( f1, 0, 0.1, 50);cout << "Mapping second function" << endl;plot( f2, 0.1, 0.5, 50);

}

70

Functions as Arguments

void plot(double (*fptr)(double), double x0, double incr, int n){

for ( int i=0; i<n; i++){cout << " x: " << x0<< " (*fptr)(x): " << (*fptr)(x0) << endl;x0 += incr;

}}double f1( double x ){ return x*2; }double f2( double x ){ return x*3-2; }