Tom Kelliher, CS23
Feb. 14, 1996
Function communication mechanisms:
Advantages:
Disadvantages:
Rule of thumb: ok to have a few global variables; should be used from many functions
What more is there to say?
Synonym: arguments
Formal parameters:
These are used to provide input values for the function, return values, or both. They have block scope, local lifetime, and are lvalues. They behave exactly as initialized local variables.
Actual parameters:
Expressions (constants and variables are a subset) in a function call that correspond to the formal parameters.
Correspondence between formal and actual parameters:
Example:
float addFloats(float, float); int i = 6; float x; x = addFloats(i + 6, 12.0); // wrong x = addFloats(i + 2.3, 12.0); // ok x = addFloats(float(i), 12.0); // ok
Default passing method: call by value
Call Semantics:
Actual parameters are rvalues
Example:
void f(void); void g(int, int); void f(void) { int i = 1; g(i, 6); cout << i << endl; // what is printed? } void g(int a, int b) { a = 12; b = 20; }
Conclusion: called function can't communicate through value parameters
Call Semantics:
Actual parameters must be lvalues
Example:
void f(void); void g(int&, int&); // reference parameter indicator void f(void) { int i = 1; g(i, 6); // constant 6 is illegal here --- not an lvalue // i + 4 would likewise be illegal cout << i << endl; // what is printed? } void g(int& a, int& b) { a = 12; b = 20; }
Conclusion: called function can communicate through reference parameters
We want to develop a program which reads a set of real numbers from a file, computes their average, and outputs the average.
Develop a program that does the following:
Inputs: Firstly, a filename. Secondly, the data (real numbers) within a file. The data will be one number per line.
Outputs: The arithmetic average of the data, or an error message if there is no data.
Formula: Sum of the data divided by the number of data items.
Initial pseudocode:
call openFile call readData call closeFile call printResults
We want to develop an interactive, menu-driven program that gives the user two choices:
Develop a program that does the following:
Inputs: User choice. If the choice is 1, an integer. If the choice is 2, an integer for the beginning of the range and another for the end of the range.
Outputs: A message stating whether or not the integer is prime, if the choice is 1. A list of prime integers in the specified range, if the choice is 2.
Formula: Check to see if the given integer n can be divided by any integer between two and the integer obtained by truncating sqrt(n) to an integer.
Initial pseudocode:
while the user wants to continue begin call printMenu set choice to enteredChoice call processChoice ask the user if they want to continue end end_while