Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.

Similar presentations


Presentation on theme: "Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to."— Presentation transcript:

1 Chapter 7 - Functions

2 Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to function’s task(s) u Two groups –Library –Programmer-defined Lesson 7.1

3 Function Categories u Return no value u Return a single value u Use “pass by reference” Lesson 7.1

4 Function Basics u Need three things to use function –Function declaration (prototype) t Indicates function exists and describes it t Must be done before use of function –Function call (invocation) t Causes control to transfer from function to function –Function definition t Header line followed by function body enclosed in braces Lesson 7.1

5 Function Declaration u Indicates function name, return type and types of values passed to function u General form ftype fname (atype, atype); u ftype is function return type u fname is function name u atype is argument type (may be different) –multiple argument separated by commas Lesson 7.1

6 Function Call u Transfers program control to function u General form fname (exp1, exp2); u fname is function name u exp1 and exp2 are arguments –Variables or constants –Called argument list Lesson 7.1

7 Function Definition u Includes function’s executable statements u General form (example with two arguments) Lesson 7.1 Function return type Function argument declarations Function body ftype fname (atype aname, atype aname) { … }

8 Argument Lists u Lists in function call and function header must coordinate –number –order –type u Example: Lesson 7.1 kinetic_energy (mass, velocity); void kinetic_energy (int m, double v) Function call in main Function header 2 arguments in each mass should be declared an integer and velocity a double in program

9 Function Arrangement u Not necessary for first function to be main u Function definition must be located outside body of any other function u Can write function declaration outside body of all functions or within function –if within, can only be called from function where declared u Function declaration MUST appear before call Lesson 7.1

10 Function Storage u When function called, memory allocated for –Variables in argument list –Variables declared in function body u When completes execution, memory freed and variable values lost –Can prevent lost and maintain u Called multiple times, allocated and freed repeatedly Lesson 7.1

11 Common Errors u Argument order not matching between function call and header u Mismatching data types u Pass more information than function needs to complete task Lesson 7.1

12 Returning a Value u Two items needed –appropriate return type for function –return statement in function u Function declaration and definition list return data type int fact(double); int fact(double arg) u return statement form return expression; Lesson 7.2 Can put expression in ( ).

13 Return Statement u Considered to be jump statement u Can appear anywhere in function body u More than one return statement can appear in function Lesson 7.2 if (expression) { return (a); } else { return (b); }

14 Returning Value From main u void type function do not return values –control transfers back to calling function automatically int main ( ) return (0); u Returns value 0 to operating system indicating normal termination Lesson 7.2

15 Recap: Pass By Value u Default u Function called –Memory set aside and value copied into new memory location –Calculations done inside function using value –When function finished executing, memory location destroyed Lesson 7.2

16 Pass By Reference u Use argument list to allow function to directly use calling function's values u Reference symbol & required in function declaration and header –Indicate arguments that will have values modified –Create aliases for original variable names Lesson 7.3

17 Pass By Reference u Example: Lesson 7.3 void func_name (int, double, double&, int&); func_name (x, y, z, a); void func_name ( int b, double c, double& d, int& e) Declaration Call Header x y z a b c d e

18 Scope u Refers to region in which declaration is active u Three kinds of scope –Block t Variable valid with block of code enclosed in braces –Function t Variable valid only within function where defined –File t Variable valid throughout all modules in file u Determined by identifier's declaration location Lesson 7.4

19 Scope Lesson 7.4 File containing functions main ( ) and calc ( ) int days; Function calc ( ) int y; for (int n=0;n<8;n++) { } Function main ( ) int x; for (int j=0;j<8;j++) { } days x x y y nj

20 Storage Classes u Allows manual modification to scope and storage rules u Stated in the declaration u Four specifiers –register : store in register –auto : memory freed after function executes –static : memory persists after function executes –extern : global variables among files Lesson 7.5

21 static u Variable maintains storage space and value after function finishes executing u Memory reserved and initialized only once –First time function called u General form: static type variable; u Can be initialized in declaration –Done once, does not initialize on other calls Lesson 7.5

22 Comparing global and static Variables u Similarity –Permanent storage created for both u Difference –Scope t Static variables accessed only from function in which declared t Global variables accessed from any function –With extern from any file Lesson 7.5

23 extern u Multiple files help manage large programs u Each compiled separately then linked to create executable file u Share variable –Variable declared as global without specifier in one file –Other files extern type variable; Lesson 7.5

24 Default Arguments u Argument assigned particular value when argument omitted in function call u Values specified in function declaration u Must have ordinary argument listed prior to default arguments Lesson 7.6 type function_name ( ordinary arguments, default arguments);

25 Using Default Arguments u Calling function –Must be called with at least the number of ordinary arguments void commute (double, double = 15.0, int = 8); commute ( 40.0 ); Call uses 40.0 for first argument, then default values: 15.0 for second argument and 8 for third Cannot specify first and third and use default for second – must have all defaults last! Lesson 7.6

26 Function Overloading u Defining two or more functions with same name u Each function takes different number of arguments –C++ knows which function is being called by counting number of arguments used –Should not use default arguments since ambiguity could result Lesson 7.7

27 Generating Random Numbers u Need three functions –rand ( ) t Returns pseudorandom integer in range 0 to 32767 –srand ( ) t Operates with rand( ) using global variable invisible to programmer –time ( ) t Returns number of seconds from midnight u Need mod (%) operator to restrict range Lesson 7.8

28 Generating a Random Number u rand( ) and srand ( ) work together –srand ( ) automatically "seeds" function rand ( ) –Functions linked through global variable u time ( ) used to get true random effect srand (time (0)); rand ( ) returns single integer time of day in seconds Call to create random number Lesson 7.8

29 Random Number in Specific Range u Use mod operator u Example: n = rand ( ); roll = (n % 6) + 1; Simulate roll of die so result should be integer from 1 to 6 Lesson 7.8

30 Summary u Define and call functions u Determine the scope of a variable u Pass values by reference u Overload functions u Create random numbers Chapter 7 Learned how to:


Download ppt "Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to."

Similar presentations


Ads by Google