90 likes | 209 Views
Class 1: Functions. Next week. Finish first homework Read 3.1-3.6 For Sept 27 Page 102, 3.10.2 (1) Playing cards Page 103, 3.10.3(1) Employee Class. What is a function?. Why is a function? Manage complexity Defensive programming Basic unit of code The ‘verb’ – gets something done
E N D
Next week • Finish first homework • Read 3.1-3.6 • For Sept 27 • Page 102, 3.10.2 (1) Playing cards • Page 103, 3.10.3(1) Employee Class cis 335 Fall 2001 Barry Cohen
What is a function? • Why is a function? • Manage complexity • Defensive programming • Basic unit of code • The ‘verb’ – gets something done • Single point of entry • A (return) type • (Often) parameters of given type cis 335 Fall 2001 Barry Cohen
Function format aType funcName(paramType paramName, paramType2 paramName2) { functionBody; return(value); } Note: no functions in function (in C++) cis 335 Fall 2001 Barry Cohen
Some terminology • Function prototype • Type • Name • Parameters • Helps type safety • Function definition • The ‘body’ • What to do • Function signature • Name • Parameters cis 335 Fall 2001 Barry Cohen
Calling a function dieValue = toss(aDie); toss(aDie); Or, in C++ dieValue = aDie.toss(); aDie.toss(); cis 335 Fall 2001 Barry Cohen
Pre- and post conditions • Precondition must be true before a block of code (function, loop) • Postcondition must be true after a block of code (function, loop) • Use asserts#include <assert.h> cis 335 Fall 2001 Barry Cohen
Parameter: Call by value • The ‘default’ type of parameter • Makes a copy of the parameter • Changing the copy doesn’t change the original • What if they have the same name? cis 335 Fall 2001 Barry Cohen
Parameter: Pass by reference • Doesn’t make a copy • Gives function access to the original • Changes are permanent • More efficient • Use const to prevent change • Why pass parameters which shouldn’t be changed? cis 335 Fall 2001 Barry Cohen