© Janice Regan, CMPT 128, Jan 2007 0 CMPT 128: Introduction to Computing Science for Engineering Students Functions Parameters passed by reference.

Slides:



Advertisements
Similar presentations
Pass by Value. COMP104 Pass by Value / Slide 2 Passing Parameters by Value * A function returns a single result (assuming the function is not a void function)
Advertisements

1 Lecture 16:User-Definded function I Introduction to Computer Science Spring 2006.
Data Structures (Second Part) Lecture 2 : Pointers Bong-Soo Sohn Assistant Professor School of Computer Science and Engineering Chung-Ang University.
Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1 ; Programmer-Defined Functions Two components of a function definition.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Introduction to Arrays.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Functions Call by reference.
1 Lecture 18:User-Definded function II(cont.) Introduction to Computer Science Spring 2006.
Computer Science 1620 Functions. Given a number n, the factorial of n, written n!, is computed as follows: note: 0! = 1 examples: n! = n x (n-1) x (n-2)
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Programmer-defined functions Development of simple functions using value parameters.
Computer Science 1620 Function Scope & Global Variables.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
Computer Science 1620 Lifetime & Scope. Variable Lifetime a variable's lifetime is finite Variable creation: memory is allocated to the variable occurs.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 6: Functions.
Call-by-Value vs. Call-by-Reference Call-by-value parameters are used for passing information from the calling function to the called function (input parameters).
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
Functions Pass by Reference Alina Solovyova-Vincent Department of Computer Science & Engineering University of Nevada, Reno Fall 2005.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
C++ Function 1. Function allow to structure programs in segment of code to perform individual tasks. In C++, a function is a group of statements that.
Variable Scope Storage Class Recursion
COMPUTER PROGRAMMING. Functions What is a function? A function is a group of statements that is executed when it is called from some point of the program.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
CPS120: Introduction to Computer Science Functions.
Functions CIS Feb-06. Summary Slide Using Functions Mathematical Functions Misc. Functions Naming Conventions Writing Functions –Function Prototype.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
1 CS161 Introduction to Computer Science Topic #10.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 COMS 261 Computer Science I Title: Functions Date: October 12, 2005 Lecture Number: 17.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Introduction to simple functions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
Function 2. User-Defined Functions C++ programs usually have the following form: // include statements // function prototypes // main() function // function.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Functions (2)
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
© Janice Regan, CMPT 128, Feb CMPT 128: Introduction to Computing Science for Engineering Students Structures.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
© Janice Regan, CMPT 128, January CMPT 128: Introduction to Computing Science for Engineering Students Introduction to Arrays.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students, continue; and break; statements.
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.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
User-Written Functions
Chapter 6: User-Defined Functions I
Introduction to Programming
Chapter 7: User-Defined Functions II
Introduction to C++ computers and programming
A Lecture for the c++ Course
CSC113: Computer Programming (Theory = 03, Lab = 01)
User-Defined Functions
Functions Pass By Value Pass by Reference
Chapter 6: User-Defined Functions I
Presentation transcript:

© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Functions Parameters passed by reference

© Janice Regan, CMPT 128, Defining a function (1)  The first line of a function is the function definition head  The function head has a type  void quadraticSolver( double coeffSq, double coeffLin, double coefConst, double *root1p, double *root2p, int *solutionTypep )  The function head has a name or identifier  void quadraticSolver( double coeffSq, double coeffLin, double coefConst, double& root1p, double& root2p, int& solutionTypep )  There is no ; at the end of a function definition head.  The function head has 0 or more parameters (arguments)  void quadraticSolver( double coeffSq, double coeffLin, double coefConst, double& root1, double& root2, int& solutionType )  Parameters are passed by value or by reference

© Janice Regan, CMPT 128, Defining a function (2)  Each of a function’s parameters have types  A function may have parameters of more than one type, each parameter must have a type  void quadraticSolver( double coeffSq, double coeffLin, double coefConst, double& xroot1, double& xroot2, int& solutionType )  Parameters passed by reference have types ending with & for example double& is a reference to a double int& is a reference to an int

© Janice Regan, CMPT 128, Sample Function void quadraticSolver( double coeffSq, double coeffLin, double coefConst, double& xroot1, double& xroot2, int& solutionType ) { //Determine the number of roots (0, 1 or 2) //Calculate the value of xroot1 // if there are 1 or 2 roots //Calculate the value of xroot2 // if there are 2 roots //These values are based on the //values of the coefficients passed into the // function (coeffSq, coeffLin, coeefConst) } Function head Function body

© Janice Regan, CMPT 128, The body of a function void quadraticSolver( double coeffSq, double coeffLin, double coefConst, double& xroot1p, double& xroot2p, int& solutionTypep ) { local variable declarations: calculations to determine values of variables passed by reference (no function value passed back for void function) return }

© Janice Regan, CMPT 128, Returning values from a function (1 )  In general a function will use the supplied actual values of the formal parameters, calculate a result, then return that result to the calling program as the value of the function call expression  In the process of calculating the return value  Values of parameters passed by value cannot be changed in the calling program by changing the copies in the called functions  Values of parameters passed by reference that are changed in the called function and are simultaneously changed in the calling function.

© Janice Regan, CMPT 128, Using a function  Once we have declared and defined a function we can then use it in the body of our function or main program  The value of the functional calling expression has the same type as the function and will contain the value returned by the function.  The identifier for a variable that is used in place of a parameter must identify a variable with the same type as that parameter.

© Janice Regan, CMPT 128, Calling a function (pointers) void quadraticSolver( double coeffSq, double coeffLin, double coefConst, double *xroot1p, double *xroot2p, int *solutionTypep )  An example of a function calling expression is quadraticSolver( coeffA, coeffB, coeffC, &answer1, &answer2, &solutionKind);  This calling express assumes that the following variables have been declared and given values in the calling program before the function is called (the statement above is executed) double coeffA, coeffB, coeffC; double answer1, answer2; int solutionKind;

© Janice Regan, CMPT 128, Calling a function (references) void quadraticSolver( double coeffSq, double coeffLin, double coefConst, double& xroot1p, double& xroot2p, int& solutionTypep )  An example of a function calling expression is quadraticSolver( coeffA, coeffB, coeffC, answer1, answer2, solutionKind);  This calling express assumes that the following variables have been declared and given values in the calling program before the function is called (the statement above is executed) double coeffA, coeffB, coeffC; double answer1, answer2; int solutionKind;

© Janice Regan, CMPT 128, What happens: calling a function  int fun1( int value1, int value1);  Main program calls function  myb =fun1(a, b); Computer memory int, myb = 0; int a = 5; Variables used in main int b = 10; myb = fun1(a, b);

© Janice Regan, CMPT 128, What happens: calling a function  int fun1( int value1, int value1);  Main program calls function  myb =fun1(a, b);  Computer makes a new ‘frame’ for executing function fun1 Computer memory int, myb = 0; int a = 5; Variables used in main int b = 10; myb = fun1(a, b);

© Janice Regan, CMPT 128, What happens: calling a function  Main program calls function  Value=fun1(value1, value2);  Computer makes a new ‘frame’ for executing function fun1  The values of a and b are copied to the new frame and placed in formal arguments value1 and value2 respectively Computer memory Variables used in fun1 int result = 0; value2 =10; value1 = 5; int, myb = 0; int a = 5; Variables used in main int b = 10; myb = fun1(a, b);

© Janice Regan, CMPT 128, What happens: calling a function  Main program calls function  Value=fun1(value1, value2);  Computer makes a new ‘frame’ for executing function fun1  The values of a and b are copied to the new frame and placed in formal arguments value1 and value2 respectively  The return value of the function, myb is calculated using value1 and value2 Computer memory Variables used in fun1 int result = 0; value2 = b; value1 = a; int, myb = 0; int a = 5; Variables used in main int b = 10; myb = fun1(a, b); Result = ?

© Janice Regan, CMPT 128, What happens: calling a function  Main program calls function  Value=fun1(value1, value2);  Computer makes a new ‘frame’ for executing function fun1  The values of a and b are copied to the new frame and placed in formal arguments value1 and value2 respectively  The return value of the function, myb is calculated using value1 and value2  The return value of the function is sent back to main Computer memory Variables used in fun1 int result = 0; value2 = b; value1 = a; int, myb = 0; int a = 5; Variables used in main int b = 10; myb = fun1(a, b); Result = ?

© Janice Regan, CMPT 128, What happens: calling a function  Main program calls function  Value=fun1(value1, value2);  Computer makes a new ‘frame’ for executing function fun1  The values of a and b are copied to the new frame and placed in formal arguments value1 and value2 respectively  The return value of the function, myb is calculated using value1 and value2  The return value of the function is sent back to main  The new ‘frame’ for fun1 is destroyed  Any changes to the values of variables in the new ‘frame’ are lost Computer memory int, myb = 0; int a = 5; Variables used in main int b = 10; myb = ?

© Janice Regan, CMPT 128, Consequences of what happens  The value of an actual parameter cannot be changed inside a function  When the new frame is made the values of the actual parameters are copied into the formal parameters  If the value of the formal parameter is changed in the function, only the value in the new ‘frame’ is changed.  When the new function ‘frame’ is destroyed, The only information remaining is the value returned to the calling function  The function cannot access the actual parameter, the value of the actual parameter is not changed

© Janice Regan, CMPT 128, Using a function  A user defined function must be  Defined After the end of the main function  Declared between the preprocessor statements and the head of the first function, the main function (global)  Called in the function using it Formal parameters of the function are replaced within the call to the function with the actual parameters, variables of the correct types from within the calling program

© Janice Regan, CMPT 128, Function to compute a factorial: Defining a user defined function int factorial( int n) { // N factorial is N*(N-1)*(N-2)*…*1 // This function computes N! (N factorial) N>0 // declare local variables int index; int product; // initialize local variables product = 1; for (index = n; i >1; i--) { product *= index; } return (product); }

© Janice Regan, CMPT 128, Declaring a user defined function: // Compute the number of combination of n items taken r at a time #include Using namespace std; // declare user defined functions to be used in main or other functions int factorial( int n); int main( ) { // declare local variables int n1, r1, c1; // initialize local variables n1 = 0; r1 = 0; c1 = 0; // read in values of r1 and n1 cout << "Enter total number of components available: "; cin >> n1; cout << "Enter number of components selected: "; cin >> r1;

© Janice Regan, CMPT 128, Calling a user defined function if(r1 <= n1) { c1 = factorial(n1) / (factorial(r1) * factorial(n1-r1)); cout << "The number of combinations is " << c1; return 0; } else { cout << "Number of components selected "; cout << "cannot exceed the total number"; return 1; }

© Janice Regan, CMPT 128, Function to compute a factorial: int factorial( int n) { // N factorial is N*(N-1)*(N-2)*…*1 // This function computes N! (N factorial) N>0 // declare local variables int index; int product; // initialize local variables product = 1; index = 0;

© Janice Regan, CMPT 128, Swap function  Consider an incorrect function trying to swap two values void swap( int value1, int value2) { double tmp; tmp = value1; value1 = value2; value2 = tmp; //The values in variables value1 and value 2 //have been exchanged }

© Janice Regan, CMPT 128, What happens: calling a function  void swap( int a, int b)  Main program calls function swap(Value1, Value2);  Computer makes a new ‘frame’ for executing function swap Computer memory int value 2 = 15; Variables used in main int value1 = 10; swap( value1, value2)

© Janice Regan, CMPT 128, What happens: calling a function  void swap( int a, int b)  Main program calls function swap(Value1, Value2);  Computer makes a new ‘frame’ for executing function swap  The values of Value1 and Value2 are copied to the formal parameters into the new frame for the function Computer memory tmp int value 2 = 15; Variables used in main Variables passed into swap b = 15; a = 10; int value1 = 10; swap( value1, value2)

© Janice Regan, CMPT 128, What happens: calling a function  void swap( int a, int b)  Main program calls function swap(Value1, Value2);  Computer makes a new ‘frame’ for executing function swap  The values of Value1 and Value2 are copied to the formal parameters into the new frame for the function  Swap exchanges the values of value1 and value2 in the function frame  Void return value: no value returned Computer memory tmp int value 2 = 15; Variables used in main Variables used in swap b = 10; a = 15; Return int value1 = 10; swap( value1, value2)

© Janice Regan, CMPT 128, What happens: calling a function  void swap( int a, int b)  Main program calls function swap(Value1, Value2);  Computer makes a new ‘frame’ for executing function swap  The values of Value1 and Value2 are copied to the formal parameters into the new frame for the function  Swap exchanges the values of value1 and value2 in the function frame  Void return value: no value returned  The function ‘frame’ for swap is destroyed  Any changes to the values of variables in the function ‘frame’ are lost  In the main program firstValue and secondValue still have their original values: They have not been swapped Computer memory int value 2 = 15; Variables used in main int value1 = 10; swap( value1, value2)

© Janice Regan, CMPT 128, Consequences of what happens  The value of a parameter cannot be changed inside a function  When the new frame is made the values of the actual parameters are copied into the formal parameters  If the value of the formal parameter is changed in the function, only the value of the formal parameter in the new ‘frame’ is changed.  When the new ‘frame’ is destroyed all record of what happened within the function is gone  Since the change was made in the function frame of the calling function is not even aware that it happened

© Janice Regan, CMPT 128, Passing variables by reference  So far we have been using the values of variables as parameters in our functions  This is called passing arguments by value  We have seen that when passing a variable by value it is not possible to change the value of that variable within the function  In some applications we need to change the value of a variable within a function  To do this we must pass the variable by reference  Instead of using the variable as our parameter, we use a reference or pointer to the variable as our argument

© Janice Regan, CMPT 128, Swap function; references  Consider a function to swap two values void swap( double& value1, double& value2) { double tmp; tmp = value1; value1 = value2; value2 = tmp; //The values in variables value1 and value2 have been //exchanged, since these values are direct references to //the actual variables in the calling function, the values in //the calling function are also changed }

© Janice Regan, CMPT 128, What happens when you call a function: 1  Main program declares variables firstValue and secondValue and initializes their values to 123 and 345  Main program calls function swap(firstValue, secondValue); Computer memory Variables used in main secondValue=34 firstValue=12 3

© Janice Regan, CMPT 128, What happens: 2  Computer makes a new ‘frame’ for executing function swap  Function swap has declaration void swap( double& value1, double& value2);  Main program calls function swap(firstValue, secondValue);  References to firstValue and secondValue are placed in the new frame  In the new frame firstValue is referred to as value1 (corresponding formal parameter of the function swap)  In the new frame secondValue is referred to as value2 Computer memory before swap Local variables used in fun1 value1 (reference to firstValue in main) value2 (reference to secondValue in main) Variables used in main secondValue=345 firstValue=123

© Janice Regan, CMPT 128, What happens: 3  In the function value1 and the value2 (value1=123, value2=456) are swapped  While swapping the values referred to by value2 and value1 are changed. Therefore, the values of firstValue and secondValue in main are changed  To swap the values in memory locations value1 and value2 tmp = value1; value1 = value2; value2 = tmp; Computer memory after swap Variables used in main secondValue=123 firstValue=345 Local variables used in fun1 value1 (reference to firstValue in main) value2 (reference to secondValue in main)

© Janice Regan, CMPT 128, What happens: 4 Computer memory  The frame created to execute the function swap is destroyed  The values of variables firstValue and secondValue have been swapped Variables used in main secondValue=123 firstValue=345

© Janice Regan, CMPT 128, Local and Global Variables  Local variables are variables that are declared and used within a particular function (or other scope)  Local variables cannot be used outside the function (scope) in which they are declared  Global variables are variables that are declared outside any function (including main)  Global variables can be accessed within any function in the program  Global variables should not be used as parameters (arguments) of functions or as variables whose values are returned by functions.  Global variables should be used with care, it is poor programming practice to use global variables rather than passing values as parameters of functions.

© Janice Regan, CMPT 128, Scope: local variable /constant  Local variables  Declared inside body of given function  Available only within that function  Not defined outside the function in which they are declared  If variable A is defined in two different functions X and Y  Variable A in function Y is a different variable from variable A in function X  Local variables are preferred  Maintain individual control over data  Functions should declare whatever local data needed to "do their job"

© Janice Regan, CMPT 128, Scope: Global Variable / constant  Declared "outside" all function bodies  Global to all functions in that file  Global declaration is common for constants:  const double TAXRATE = 0.05;  Declare globally so constant is in scope of all functions  Global variables?  Possible, but SELDOM-USED  Dangerous: value can be changed anywhere, very difficult to determine what the value should be in a large complicated program

© Janice Regan, CMPT 128, Local Variable declarations  You must declare local variables used in the function  DO NOT declare formal parameters of the function within the function.  If you declare parameter variables they will be ‘hidden’ and will not always have the values you expect  Initialize the local variables in your function  DO NOT initialize parameters within your function  The value of the parameter you supply when you call the function will be replaced by the value in your initialization

© Janice Regan, CMPT 128, Avoid a common problem  A variable X declared inside the main function is not the same variable as a variable X declared in another function  The variable X defined in the main function is local to the main function, and only exists in the main function  The variable X defined in the other function exists only in the other function, it is not accessible in the main function. IT IS NOT THE SAME VARIABLE X as the X in the main function

© Janice Regan, CMPT 128, Nested Scope, Block Scope  A variable declared in a block (within a pair of { }) only exists in that block  If you do not declare variables at the start of your program you may declare them within a pair of { } nested inside your function In this case the variables will not exist outside the { } in the remainder of the function If you try to use the variable outside the { } it will not exist and your program will fail

© Janice Regan, CMPT 128, Blocks  Declare data inside compound statement  Called a "block"  Has "block-scope"  Note: all function definitions are blocks!  This provides local "function-scope"  Loop blocks: for (int ctr=0;ctr<10;ctr++) { sum+=ctr; }  Variable ctr has scope in loop body block only