Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "© Janice Regan, CMPT 128, Jan 2007 0 CMPT 128: Introduction to Computing Science for Engineering Students Functions Parameters passed by reference."— Presentation transcript:

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

2 © Janice Regan, CMPT 128, 2007-2012 1 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

3 © Janice Regan, CMPT 128, 2007-2012 2 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

4 © Janice Regan, CMPT 128, 2007-2012 3 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

5 © Janice Regan, CMPT 128, 2007-2012 4 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 }

6 © Janice Regan, CMPT 128, 2007-2012 5 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.

7 © Janice Regan, CMPT 128, 2007-2012 6 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.

8 © Janice Regan, CMPT 128, 2007-2012 7 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;

9 © Janice Regan, CMPT 128, 2007-2012 8 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;

10 © Janice Regan, CMPT 128, 2007-2012 9 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);

11 © Janice Regan, CMPT 128, 2007-2012 10 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);

12 © Janice Regan, CMPT 128, 2007-2012 11 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);

13 © Janice Regan, CMPT 128, 2007-2012 12 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 = ?

14 © Janice Regan, CMPT 128, 2007-2012 13 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 = ?

15 © Janice Regan, CMPT 128, 2007-2012 14 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 = ?

16 © Janice Regan, CMPT 128, 2007-2012 15 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

17 © Janice Regan, CMPT 128, 2007-2012 16 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

18 © Janice Regan, CMPT 128, 2007-2012 17 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); }

19 © Janice Regan, CMPT 128, 2007-2012 18 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;

20 © Janice Regan, CMPT 128, 2007-2012 19 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; }

21 © Janice Regan, CMPT 128, 2007-2012 20 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;

22 © Janice Regan, CMPT 128, 2007-2012 21 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 }

23 © Janice Regan, CMPT 128, 2007-2012 22 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)

24 © Janice Regan, CMPT 128, 2007-2012 23 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)

25 © Janice Regan, CMPT 128, 2007-2012 24 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)

26 © Janice Regan, CMPT 128, 2007-2012 25 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)

27 © Janice Regan, CMPT 128, 2007-2012 26 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

28 © Janice Regan, CMPT 128, 2007-2012 27 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

29 © Janice Regan, CMPT 128, 2007-2012 28 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 }

30 © Janice Regan, CMPT 128, 2007-2012 29 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

31 © Janice Regan, CMPT 128, 2007-2012 30 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

32 © Janice Regan, CMPT 128, 2007-2012 31 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)

33 © Janice Regan, CMPT 128, 2007-2012 32 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

34 © Janice Regan, CMPT 128, 2007-2012 33 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.

35 © Janice Regan, CMPT 128, 2007-2012 34 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"

36 © Janice Regan, CMPT 128, 2007-2012 35 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

37 © Janice Regan, CMPT 128, 2007-2012 36 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

38 © Janice Regan, CMPT 128, 2007-2012 37 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

39 © Janice Regan, CMPT 128, 2007-2012 38 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

40 © Janice Regan, CMPT 128, 2007-2012 39 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


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

Similar presentations


Ads by Google