© 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