Functions: Supplemental Lecture CMSC 104—Section 4, Spring 2011 Purpose of Functions • Three main motivations for dividing our program into smaller pieces: – Sharing a chunk of logic • We often want to do the exact same thing in several places in a given program – Modularizing • Human beings think better in smaller chunks • Even for large lists, breaking things up into hierarchies helps – Easy reuse • Code has already been tested in other cases • Functions are modern way of creating these modular chunks of reusable code Early Modules: “goto”s • In the old days (before structured programming) you used “goto” to jump to another chunk of code – Had to somehow communicate where to “goto” back to. – Led to contorted flow of control: • “goto”s are BAD! Functions for Reuse: Before functions: do { input = prompt(“Enter number:”); input = parseInt(input): if (input < 0) { alert(“Number must be > 0”); } } while (input < 0); num1 = input; do { input = prompt(“Enter number:”); input = parseInt(input): if (input < 0) { alert(“Number must be > 0”); } } while (input < 0); num2 = input; do { input = prompt(“Enter number:”); input = parseInt(input): if (input < 0) { alert(“Number must be > 0”); } } while (input < 0); num3 = input; do { input = prompt(“Enter number:”); input = parseInt(input): if (input < 0) { alert(“Number must be > 0”); } } while (input < 0); num3 = input; With functions: function getPositive() { do { input = prompt(“Enter number:”); input = parseInt(input): if (input < 0) { alert(“Number must be > 0”); } } while (input < 0); return input; } num1 num2 num3 num4 = = = = getPositive(); getPositive(); getPositive(); getPositive(); Structured version of “goto”: Function Calls Function calls are still essentially an alteration of flow of control, but: • Where to jump to, is meaningfully named • Where to return to, is automatically managed • Protected context is created – local variables, parameters Functions Have Protected Scope • It is as though function’s code is executed inside a sealed box • Local variables cannot be seen by outside world – All variables used in function should be local – Local variables recreated anew with each call – Local variables are destroyed upon return • Scope is “per call”—more on this later… Function Scope (cont) • Get all information about task at hand from parameters – Inside function, parameters are effectively local variables – Start off with a copy of the values caller used as actual parameters • Only pass back information to outside world via return value Designing Functions • Should package up an intuitively related set of steps – Good e.g.: function to prompt user, get input, test validity, and repeat until user enters good value – Bad e.g.: get move from user, then if deck empty, shuffle new deck, then compute computer’s play. • How to break things up into functions is an art – Some helpful heuristics: • # lines of code • Repeated sections of code Nesting Function Calls • A function can easily call other functions for help – No reason not to be able to! • Analogous to nesting control structures: – If/else blocks – while loops • A function can even call itself!! – Recall: we said function’s scope (set of local variables, parameters, what line it is up to, etc.) is per-call – This is true even when a function calls itself • (But why would you want to do this?? Hint: see exercise #5) Expressions as Arguments • Terminology: “arguments” == “actual parameters” • Can use any expression in place of an argument to a function call • Can even use other function calls – Value of argument is whatever is returned by the function call – E.g.: input_num = parseInt(prompt(“Enter a number”)); In-Class Exercises For each task, write a function to do it, then call it from inside your <body> section: 1. A function that outputs “Hello, world” with an alert box 2. A function that takes 1 parameter, and outputs it with an alert box. 3. A function that takes 2 numerical parameters, and outputs the sum with an alert box 4. A function that takes 2 numerical parameters, and returns their sum; caller should output result with an alert box. 5. A function that computes the “factorial(x)” function, and returns the value of “X!”; caller should output answer. 6. Extra Credit: write “factorial(x)” without using loops!