C++ Pointer and Functions

Slides:



Advertisements
Similar presentations
Parameter Passing. Variables: lvalues and rvalues In the assignment statement “X=Y”, variables X and Y are being used in different ways. Y is being used.
Advertisements

Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
Kernighan/Ritchie: Kelley/Pohl:
Chapter 5 Functions.
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
1 Lecture 18:User-Definded function II(cont.) Introduction to Computer Science Spring 2006.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Parameter Passing. Expressions with lvalues and rvalues An expression has an lvalue/rvalue if it can be placed on the left/right side of an assignment.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Pointers. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program execution.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Review of C++ Programming Part II Sheng-Fang Huang.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
February 11, 2005 More Pointers Dynamic Memory Allocation.
This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Object-Oriented Programming in C++
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Section 4 - Functions. All of the programs that we have studied so far have consisted of a single function, main(). However, having more than one function.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
Liang, Introduction to C++ Programming, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Advanced Function Features.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Review 1 List Data Structure List operations List Implementation Array Linked List.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Functions, Scope, and The Free Store Functions Functions must be declared by a function prototype before they are invoked, return_type Function_name(type,
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Chapter 5 Functions.
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Pointers, Dynamic Data, and Reference Types
6 Chapter Functions.
Memory Allocation CS 217.
Pointers.
7 Arrays.
Dynamic Memory.
Presentation transcript:

C++ Pointer and Functions SECTION 3 C++ Pointer and Functions

L-value and R-value L-Value and R-Value Two 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 operator requires an l-value.

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 x 1 = y; // error. no l-value for literal constant 1. ++ x; // x=x+1 ++ 10; // ? Operand for ++ operator requires must be an L value

Pointer definition Syntax: base type * pointer name; where base type defines the type of variable the pointer points to. Example: int * ptr1; // a pointer to integer. int * * ptr2; // a pointer to pointer to integer int * ptr1, ptr2; // a pointer and an integer

Figure of Memory Allocation dynamic objects memory managed by programmer;by explicitly call of new/delete Function 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

Memory Allocation In 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; }

Memory Allocation

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; }

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

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

Dynamic Allocation of Multi-dimensional Array for(int i=0; i<m; i++) //each pointer in the array points to a[i] = new int[n]; //an array of integer //the size of these integer arrays is n cout <<''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 memory delete [] a[i]; delete [] a; }

Dynamic Allocation of Multi-dimensional Array

Dynamic Allocation of Multi-dimensional Array

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.

Dynamic Allocation of Multi-dimensional Array Related problems: – memory leak – dangling pointer

Dynamic Memory Allocation Questions: Does the statement delete ptr; delete the pointer ptr or the object being referred by ptr?

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 !

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.

C++ Reference Type Example: //sam7.cpp int a, b=5; int &ref = a; // a and ref both refer to same memory location! // ref is an alias for a a = 3; ref = 3; // both affect a ref = b; //ref=5 ref++; //ref=6 //Compared to pointer: int *ptr; // ptr is a new object ptr = &a; *ptr = 3; ptr = &b; // ok

C++ Reference Type Reference types are usually used as function parameters. It can – increase code clarity, – reduce function parameter costs, – optimize compilation.

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

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; }

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 integer void g(); // declaration of g: // g has no argument and returns nothing

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 ( ).

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[])

Parameter Type Checking The arguments of every function call are type-checked during compilation. If there is a type mismatch, implicit conversion is applied if possible. //sam8.cpp void f( int ){ /* ... */ } int x = 0; bool flag = true; char c = 'a'; f( 10 ); // exact match f( x ); // exact match f( flag ); // match with a promotion f( c ); // match with a promotion f( 12.34 ); // match with a standard conversion f( "hello" ); // mismatch f( 12, 3 ); // mismatch

Call by Value The 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;

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

Call by Value

Call by Value

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); }

Call by Reference void swap( int *a, int *b){ int tmp; tmp = *a; *a = *b; *b = tmp; }

Call by Reference The reference operator is usually used to specify a call-by-reference parameter in C++. Example 1: //sam9.cpp void f(int a, int &b); int main(){ int i = 0; int j = 0; f(i, j); cout << i <<'\n'; //i=0 cout << j <<'\n'; //j=1 } void f(int a, int &b){ a++; b++;

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;

Call by Reference

Return by Value When 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 - 100 return x; } int main(){ int y = f(10);

Return by Value

Return by Reference When a function returns an object by reference using reference operator (&), the object is returned as l-value. Example: //sam10.cpp int& f( int *ptr, int x ){ return ptr[x]; } int main(){ int a[100]; cout<<f( a, 10 )<<endl;

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 }

Array Parameters When an array is used as a function argument, the address of the array is passed. Example: //sam11.cpp void 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';

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.

Array Parameters To avoid modifying the local copy of array elements, we can use the const specifier. void display(const int *num, int size){ // ... }

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 }

Default Argument In 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 ); // ok f( 1 ); // ok, m=12.34 f(); // error! no default value for x }

Default Argument Default arguments can be provided by trailing arguments only. void f( int x=1, double m, char s='a'); // wrong void f( int x=1, double m=12.34, char s); // wrong void f( int x, double m, char s='a'); // ok

Default Argument Default arguments should be supplied in a function declaration, not in a function definition. Example: // file f.h void f(int, int); // file f.cpp void f( int a = 2, int b = 3){ // ... }

Default Argument Correct version: // file f.h void f(int a = 2, int b = 3); // also ok: void f(int = 2 , int = 3); // file f.cpp void f( int a, int b){ //... }

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 );

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 );

Scope and Lifetime Two 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.

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

Local Scope and Local Objects A local scope is the program text enclosed in braces {}. Each function block represents a distinct local scope. An object declared in local scope is a local object to the block. A local object can be – Automatic object – Static local object

Local Scope and Local Objects An 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;

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

Static Local Objects Example: void f(); int main(){ f(); f(); f(); } static int i; // initialized to 0 by default int x = 0; cout <<''i = '' << i <<''x = '' << x <<'\n'; i = i+1; x = x+1; What is the output?

Static Local Objects Note: The word static has double meaning in C++: 1. regarding memory allocation. 2. regarding scope of variable.

Dynamically Allocated Objects A 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; // ... }

Function Overloading In C++, functions can be overloaded if they have the same name, declared in the same scope and have different signatures. The signature of a function consists of the number, data types and order of the function’s parameter list. Function overloading is a form of polymorphism.

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);

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 );

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

Function Overloading Resolution The 3 steps of overloaded function resolution. 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 is ambiguous.

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 ); }

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.

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++)

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 ); }

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 of function calls, while preserves the benefits of abstraction.

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 double fptr = f1; // ok fptr = &f2; // ok fptr = f3; // wrong result = (*fptr)( 12.34 ); // ok result = fptr( 12.34); // ok

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); }

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; }