1 / 31

Fun ctions (they can be fun...)

Fun ctions (they can be fun...). CS31 Discussion. OUTLINE: Functions: Passing Data, Return Values Declaring and Defining Functions Parameters: Call-by-value and Call-by-reference (for a future discussion). TA: Peter Wu (Slides adopted from a previous CS31 class). Functions.

elaine-key
Télécharger la présentation

Fun ctions (they can be fun...)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Functions (they can be fun...) CS31 Discussion • OUTLINE: • Functions: Passing Data, Return Values • Declaring and Defining Functions • Parameters: Call-by-value and Call-by-reference (for a future discussion) TA: Peter Wu (Slides adopted from a previous CS31 class)

  2. Functions In a well-written program, the mainfunction calls other functions to do the work of the program. main should not do all of the work itself: int main() { GetTestScores(); // call to a function ComputeAverage(); PrintScores(); }

  3. Functions • Question: Let’s say that we want to define a function that takes no inputs and prints out “Hello” • What is our program structure going to look like?

  4. A Simple Program With Functions void praise(); void tease(); //declarations void praise() { cout << “totally cool\n”; } void tease() { cout << “would like to be ”; praise(); } int main() { cout << “CS student is “; praise(); cout << “Engineer“; tease(); cout << “The end.\n”; } This program has three functions: main, praise,tease As always, our program starts in main! When we reach a function, we run the logic in the function and then continue with the next line of the program. CS student is totally cool Engineer would like to be totally cool The end.

  5. Passing Data To Functions void cube(); void cube() { // TODO: implement this function // properly } int main() { int value; cout >> “Enter a value: ”; cin >> value; //TODO: Call cube with value } QUESTION: What if we wanted a function to take inputs? For example, what if we wanted cube(x) to display the result of x * x * x ?

  6. c n value c n 93 2 3 8 2 27 Passing Data To Functions 2 void cube( int n ); void cube( int n ) { int c = n*n*n; cout << n << “ cubed is “ << c << “\n”; } int main() { int value; cout >> “Enter a value: ”; cin >> value; cube(value); cube(value+1); } 3 To pass data, when we call the function, we place the value(s) we want to send in between the parentheses. 3*3*3 2*2*2 When we define the function, we specify the type and name of each parameter in between the parentheses. 2 Enter a value: 2 3 2 cubed is 8 3 cubed is 27

  7. Passing Data To Functions void cube( int n ); void cube( int n ) { int c = n*n*n; cout << n << “ cubed is “ << c << “\n”; } int main() { int value; cout >> “Enter a value: ”; cin >> value; // a common mistake: cube(int value); cube(value+1); } Note: a common mistake is to include the variable type along with the variable name when calling the function.

  8. Returning Data From Functions void cube( int n ); void cube( int n ) { int c = n*n*n; } int main() { int value, result; cout >> “Enter a value: ”; cin >> value; cube(value); //TODO: I want to save the //result of cube(value) into //the variable ‘result.’ cube(value+1); } Sometimes you need to send a value back from a function to the caller of the function. How can we change this program so that main can the result of cube(value) ?

  9. 314 314 a r area rad 913 71 10 -1 10 Returning Data From Functions //declarations.. double ComputeArea( double rad ) { double a; a = 3.14 * rad * rad; return( a ); } int main() { double r, area; cout >> “Enter radius: ”; cin >> r; area = ComputeArea( r ); cout << “Area: “ << area; } 10 3.14 * 10 * 10 314 We’ll need to use the return statement in our function. 10 314 Enter radius: 10 Area: 314.00

  10. Function Prototypes (Declaring Functions) int main() { int n; cin >> n; UCLARules(n); } void UCLARules(int x) { int j; for (j=0;j<x;j++) cout << “UCLA Rules\n”; } void UCLARules(int x) { int j; for (j=0;j<x;j++) cout << “UCLA Rules\n”; } int main() { int n; cin >> n; UCLARules(n); } What’s the difference between these two programs?

  11. Function Prototypes In this example, a function (main) calls another function (UCLARules) that is defined later in the program. int main() { int n; cin >> n; UCLARules(n); } void UCLARules(int x) { int j; for (j=0;j<x;j++) cout << “UCLA Rules\n”; } This is like a novel that refers to a character, but the character is introduced in a later chapter. It’s confusing!

  12. Function Prototypes This is also confusing for the C++ compiler. When compiling the main function, it sees the function call to UCLARules but it doesn’t know about this function yet. This results in an error. int main() { int n; cin >> n; UCLARules(n); } void UCLARules(int x) { int j; for (j=0;j<x;j++) cout << “UCLA Rules\n”; }

  13. Function Prototypes ; If you would like to call a function defined later in the program, you must add a special line called a prototypeabove your call to the function. int main() { int n; cin >> n; UCLARules(n); } void UCLARules(int x) { int j; for (j=0;j<x;j++) cout << “UCLA Rules\n”; } Simply copy the function’s header line above the first reference to the function. void UCLARules(int x) Then add a semicolon at the end. Think of this as an introduction to your new function. It tells your other functions how to use it, even if its defined later.

  14. The Function Definition I return decimal-point numbers. The function definition is where you put the function’s actual logic. double ComputeArea( double rad ) { double a; a = 3.14 * rad * rad; return( a ); } int main() { double r, area; cout >> “Enter radius: ”; cin >> r; area = ComputeArea( r ); cout << “Area: “ << area; } double ComputeArea( double rad ) { double a; a = 3.14 * rad * rad; return( a ); } Each func. def. has: return( a ); • A function header line that specifies: a. The func’s name b. The func’s parameters b. The type of value the function returns. • The function body. • A return statement that sends a value back to the caller. (optional for void type)

  15. //‘a’ is local to ComputeArea //‘area’ is local to main Local and Global Variables local variable: variables local to the function (sometimes called an ‘automatic variable’) Name some of the local variables on the left. double ComputeArea( double rad ) { double a; a = 3.14 * rad * rad; return( a ); } int main() { double area; area = ComputeArea( 4.0 ); cout << “Area is: “ << area; } This is different from global variables, which can be accessed by any function. Oh, these are hard to track and can result in messy code. We will NOT be using them in CS31. // example of a global variable int global_variable; //consts are always fine to use! const double PI = 3.14;

  16. Function Parameters x 4.0 A function may have one or more formal parameters They are treated just like any other local variable. double ComputeArea( double rad ) { double a; a = 3.14 * rad * rad; return( a ); } int main() { double area; area = ComputeArea( 4.0 ); cout << “Area is: “ << area; } // ERROR! char x = ‘A’; When you call the function, the parameter value from the calling function is copied into the parameter variable. You must make sure that both parameters match.

  17. Function Parameters #include <iostream> #include <cmath> using namespace std; double TotalFluid(int blah, double whatever) { double totalOunces; totalOunces = blah * whatever; return(totalOunces); } int main() { int magic_num = 4; int total; total = TotalFluid( magic_num , .52 ); cout << “Ounces of fluid: “ << total; } Functions may have multiple parameters. Each formal parameter should be separated by a comma and must have its own type and name specified . Make sure that the type of each actual parameter matches the type of each formal parameter!

  18. char your_grade; your_grade = ‘A’; return(your_grade); char your_grade; your_grade = ‘A’; return(your_grade); // ERROR! Returning from a Function A function can return any single type of value it likes: int, char, string, double, bool, etc. double ComputeArea( double rad ) { double a; a = 3.14 * rad * rad; return( a ); } int main() { double area; int level; area = ComputeArea( 10 ); ... double In this case, our top function has a return type of “double” so it should return double-type values. For instance, it shouldn’t try to return char values. This may result in either a compiler error or a run-time error!

  19. 180 nh age 9991 18 Returning from a Function When the program reaches a return statement… The current function ends immediately and sends its result value back to the caller. 18 int ComputeCodingSkills(int age) { if (age < 33) return(age * 10); } int main() { int nh; nh= ComputeCodingSkills(18); cout << “Will has level“ << nh << “ skillz!\n”; } 18 < 33? 180 18*10 cout << “too pro for me!\n”; return(age*100); Will has level 180 skillz! 180

  20. grade 85 Returning from a Function void PrintGrade(int grade) { if (grade >= 90) { cout << “A”; return; } if (grade >= 80) { cout << “B”; return; } cout << “Study harder!”; } int main() { PrintGrade(85); cout << “Done!\n”; } If a function doesn’t need to return a value, it should have a void return type. This means: “I don’t return any value.” In this case, you may still use the return statement to immediately exit the function, but you can’t specify a value.

  21. Variable Rules double ComputeArea( double rad ) { double a; a = 3.14 * rad * rad; return( a ); } int main() { double area; area = ComputeArea( 4 ); cout << “Area is: “ << area; } A function may have its own private“local” variables. A function can only access its own variables, but not other function’s variables. cout << area; // ERROR! So ComputeArea can access a and rad but can’t access the area variable. Similarly, main can access area but cannot access the rad or a variables. cout << rad; // ERROR! Why is this important?

  22. Functions: Understanding Parameters n x 12 void change_me(int x); int main() { int n; cout << "Enter a #: "; cin >> n; cout << n << endl; change_me(n); cout << n << endl; } // definition void change_me(int x) { x = 12; } • Questions: • What does this program print? • Does the value of n change? • Why or why not? 3 Remember: all local variables/parameters go away when the function exits… 3 Enter a #: 3 3 3 3

  23. Functions: Understanding Parameters n n 12 void change_me(int x); int main() { int n; cout << "Enter a #: "; cin >> n; cout << n << endl; change_me(n); cout << n << endl; } // definition void change_me(int n) { n = 12; } Ok – how about this one? Be careful! 3 The parameters are Call-by-value 3 Enter a #: 3 3 3 3

  24. x temp b a y 20 20 10 10 10 10 20 Functions and Reference Parameters 10 20 void swap(int a, int b) { int temp; temp = a; a = b; b = temp; } int main() { int x = 10, y = 20; swap( x, y); cout << x << endl; cout << y << endl; } What’s wrong with this program? What is it supposed to do? 10 20 10, 20

  25. Functions and Reference Parameters The previous program was supposed to swap main’s x and y variables. It didn’t work because the swap function swaps its own local variables and not main’s variables. So how can we let one function modify another function’s variables? Answer: Using references! (call-by-reference)

  26. x temp y (ref) b (ref) a 20 10 10 20 10 Functions and Reference Parameters void swap(int a, int b) { int temp; temp = a; a = b; b = temp; } int main() { int x = 10, y = 20; swap( x, y); cout << x << endl; cout << y << endl; } If you place an & between a formal parameter’s type and its name, it becomes a referencevariable. & & Lets see what happens! 20 10

  27. Reference Parameters You can use a reference parameter to modify a variable from the calling function. Any time you access the reference parameter, you’re really accessing the variable in the calling function. Syntax: Place an & between a parameter’s type and its name in the function header: void SomeFunction(int & doe, double & ray, string & mi) { … etc…

  28. Functions and Reference Parameters msg (ref) s “UCLA ” “UCLA fight, ” “UCLA fight, fight” void cheer(string &s) { s = s + “fight, ”; } int main() { string msg = “UCLA "; cheer(msg); cout << msg << endl; cheer(msg); cout << msg << endl; } What does it print? s = “UCLA “ + “fight, “ s = “UCLA fight, “ + “fight, “ Let’s work through it! UCLA fight, UCLA fight, fight

  29. Functions and Reference Parameters void zero_it( int &i ) { i = 0; } int main() { double d = 10; zero_it(d); // SYNTAX ERROR } What’s wrong with it? If you’re going to pass a value to a function with a reference parameter, the types must match exactly! The type of the reference parameter must match exactly with the type of the argument. In this case, we’re trying to pass a double variable to an integer parameter. BAD!

  30. (ref) x (ref) y a 50.0 53.0 57.0 (Hard) Reference Parameters void add4(double &x) { x += 4; } void add7(double &y) { y += 3; add4(y); } int main() { double a = 50.0; add7(a); cout << “50 plus 7 is: “ << a; } Lets look at another contrived example… 50 plus 7 is 57.000

  31. The End… or is it? • So that concludes functions… • "Home computers are being called upon to perform many new functions, including the consumption of homework formerly eaten by the dog.“

More Related