Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to...

25
Chapter 7 - Functions
  • date post

    19-Dec-2015
  • Category

    Documents

  • view

    219
  • download

    1

Transcript of Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to...

Chapter 7 - Functions

Functions

Code group that performs single task Specification refers to what goes into and

out of function Design refers to function’s task(s) Two groups

– Library– Programmer-defined

Lesson 7.1

Function Categories

Return no value Return a single value Use “pass by reference”

Lesson 7.1

Function Basics

Need three things to use function– Function declaration (prototype)

Indicates function exists and describes it Must be done before use of function

– Function call (invocation) Causes control to transfer from function to function

– Function definition Header line followed by function body enclosed in

braces

Lesson 7.1

Function: 5 Steps

1. Prototype

2. Header including parameters

3. Body of functions

4. Return statement

5. Function call or invocation

Function Declaration Indicates function name, return type and

types of values passed to function General form ftype fname (atype, atype); ftype is function return type fname is function name atype is argument type (may be different)

– multiple argument separated by commas

Lesson 7.1

Function Call

Transfers program control to function General form fname (exp1, exp2); fname is function name exp1 and exp2 are arguments

– Variables or constants– Called argument list

Lesson 7.1

Function Definition

Includes function’s executable statements General form (example with two arguments)

Lesson 7.1

Function return typeFunction return type

Function argument declarationsFunction body

ftype fname (atype aname, atype aname) { … … }

Argument Lists

Lists in function call and function header must coordinate– number– order– type

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

Function Storage

When function called, memory allocated for– Variables in argument list– Variables declared in function body

When completes execution, memory freed and variable values lost– Can prevent lost and maintain

Called multiple times, allocated and freed repeatedly

Lesson 7.1

Common Errors

Argument order not matching between function call and header

Mismatching data types Pass more information than function needs

to complete task

Lesson 7.1

Returning a Value

Two items needed– appropriate return type for function– return statement in function

Function declaration and definition list return data type

int fact(double); int fact(double arg) return statement form return expression;

Lesson 7.2

Can put expression in ( ).

Return Statement

Considered to be jump statement

Can appear anywhere in function body

More than one return statement can appear in function

Lesson 7.2

if (expression) { return (a); }else { return (b); }

Returning Value From main

void type function do not return values– control transfers back to calling function

automatically

int main ( )

return (0); Returns value 0 to operating system

indicating normal termination

Lesson 7.2

Recap: Pass By Value

Default 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

Pass By Reference

Use argument list to allow function to directly use calling function's values

Reference symbol & required in function declaration and header– Indicate arguments that will have values

modified– Create aliases for original variable names

Lesson 7.3

Pass By Reference

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

Scope Refers to region in which declaration is active Three kinds of scope

– Block Variable valid with block of code enclosed in braces

– Function Variable valid only within function where defined

– File Variable valid throughout all modules in file

Determined by identifier's declaration location

Lesson 7.4

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

days days

days days

x

x y

y

nj

Default Arguments

Argument assigned particular value when argument omitted in function call

Values specified in function declaration Must have ordinary argument listed prior to

default arguments

Lesson 7.6

type function_name ( ordinary arguments, default arguments);

Using Default Arguments

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 defaultvalues: 15.0 for second argument and 8 for third

Cannot specify first and third anduse default for second – must haveall defaults last!

Lesson 7.6

Generating Random Numbers

Need three functions– rand ( )

Returns pseudorandom integer in range 0 to 32767

– srand ( ) Operates with rand( ) using global variable invisible

to programmer

– time ( ) Returns number of seconds from midnight

Need mod (%) operator to restrict range

Lesson 7.8

Generating a Random Number

rand( ) and srand ( ) work together– srand ( ) automatically "seeds" function rand ( ) – Functions linked through global variable

time ( ) used to get true random effect

srand (time (0));

rand ( ) returns single integer time of dayin seconds

Call to createrandom number

Lesson 7.8

Random Number in Specific Range

Use mod operator Example:

n = rand ( ); roll = (n % 6) + 1;

Simulate roll of die so result should be integer from 1 to 6

Lesson 7.8

Summary

Define and call functions Determine the scope of a variable Pass values by reference Create random numbers

Chapter 7

Learned how to: