108
Functions Structured Programming 256 Chapter 6

Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Embed Size (px)

Citation preview

Page 1: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Functions

Structured Programming 256

Chapter 6

Page 2: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

FunctionsFunctions prototypesprototypes

argumentsarguments

overloadingoverloading

return valuesreturn values part part

II

Page 3: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Functions

are subprograms in C++ . perform a specific task. can act on data and return a value. Every C++ program has at least one

function: main().

are self-contained blocks of code, the inner workings of which are invisible to the remainder of the program.

Page 4: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Functions

• Why use functions? make programs easier to write, debug and

maintain - divide and conquer!

Two main types of functions: predefined -- found in the header files user-defined -- today’s topic

Page 5: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function - an example

• {• int var1=1, var2=2, var3=3,

var4=4;• function1(“ASU”, var1);• some statements;• function2(var4, var3);• function3(var2);• }

Page 6: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function - an example

•void function1(char name, int place){ cout << name << “ is #” << place << endl;}

•void function2(int al, int mel){ cout <<“var3 x var4 = “ << mel / al<<endl;}

•void function3(int casey){ cout << casey << “ is the value in var2\n”;}

Page 7: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function properties

may be called may be passed data called arguments may return a value to the calling

program will not change the data stored in a

received variable unless specifically instructed to do so

Page 8: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

© 2000 Scott S Albert

Functions

• 1. #include <iostream.h>• 2. void demofunction(void);

• 3. void main(void) 4. { 5. cout << "In main\n"; 6. demofunction(); 7. cout << "Back in main\n"; 8. }

• 9. void demofunction(void) 10. { 11. cout << "In DemoFunction\n"; 12. cout << “Still in function.\n”; 13. }

Page 9: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

© 2000 Scott S Albert

Function

Output

• 5. In main

• 6. (calls function - 11.) In Demo Function

• - 12.) Still in function.

• 7. Back in main

Line #Line #

* * * *

Page 10: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function declaration

• double Pythagorus( double, double );double Pythagorus( double, double );

• data types onlydata types only

Page 11: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function Syntax

• Syntax•

function header line function header

{{statementsstatements function bodyfunction body

}}

*

Page 12: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function Header Syntax

• Syntax

• typetype function_name(parameters)

no ;ExampleExample

doubledouble Pythagorus(double a, double b)

Page 13: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

• ExampleExample

double Pythagorus(double a, double b)

Function Definition

* *

no ;{type var

{double c;

c = sqrt(a*a + b*b);returnreturn c;

}

Page 14: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function Call

• void main(void)• {• cout << “The hypotenuse is “• << Pythagorus(12, 5);• }

• OUTPUT• The hypotenuse is 13

Page 15: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Program Structure• #include <iostream.h>

function prototypes;•

void main(void)• {• variable declarations;

statements[including function calls]

• }

• function definition(s)

Page 16: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function Prototypes

• Syntaxreturn type function_name(type);

ExampleExampledoubledouble PythagorusPythagorus((doubledouble,, double double););

*

Page 17: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function Prototypes

• ExamplesExamples•

doubledouble PythagorusPythagorus((doubledouble,, double double););

• voidvoid do_stuffdo_stuff((voidvoid););

• doubledouble times-emtimes-em((intint,, int int,, int int,, intint););

• doubledouble myfuncmyfunc((doubledouble,, int int););

• voidvoid print_emprint_em((charchar,, double double););

Page 18: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function Calls

• SyntaxSyntaxfunction_name(arguments);

• ExampleExamplePythagorus(3.0, 4.0);

* *

Page 19: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function CallsFunction Calls

find_max(firstnum, secnum);

get f

irstn

um

get f

irstn

um

find_max( ,, )865865

get s

ecnu

m

get s

ecnu

m

* * * * * *

865865firstnumfirstnum

90909090secnumsecnum

memorymemory

90909090

Page 20: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function Calls

• answer = Pythagorus(3.0,4.0);• cout << “The hypotenuse = “• << answer << endl;

*

cout << “The hypotenuse = “ << Pythagorus(3.0,4.0)<<endl;

Page 21: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function Calls

• answer = Pythagorus(3.0,4.0);• answer answer = answer * 100; answer * 100;• cout << “The hypotenuse = “• << answer << endl;

*

cout << “Hypotenuse = “ << Pythagorus(3.0,4.0) * 100* 100 <<endl;

Page 22: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Program Structure• #include <iostream.h>

function prototypes;•

void main(void)• {• variable declarations;

statements[including function calls]

• }

• function definition(s)

Page 23: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Program Structure

main functionsquare callcube call

square function

cube function

#include <iostream.h>

square prototypesquare prototypecube prototypecube prototype

Page 24: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Program Structure

• int square(int); // function prototype• int cube(int); // or function declaration

• void main(void)• {• int x = 8;• cout <<“The square is “<< square(x) square(x) <<‘\n’;• cout <<“The cube is “ << cube(x) cube(x) <<endl;• . . .• }• int square(int n) // function definition• { continued on next slide

Page 25: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Program Structure• int square(int n) // function definition• {• int answer;• answer = n*n;• return answer;• }

• int cube(int n) // function definition• {• int answer;• answer = n*n*n;• return answer;• }

{{OROR return n*n;return n*n;

{{OROR return n*n*n;return n*n*n;

*

Page 26: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function SummaryPrototype

typetype function_namefunction_name((parameter parameter typestypes));;

Callfunction_namefunction_name((actualactual parametersparameters));;

Definition formalformal typetype function_namefunction_name((parameter parameter types types & namesnames)){

}

double Pythagorus(double, double);

Pythagorus(height, base);

double Pythagorus(double a, double b) * * * * *

Page 27: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function Overloading• Two or more distinct functions may have the

same name.

• The data types of the arguments in the function calls must match those in the prototypes and in the definitions.

• The same function is given multiple definitions or implementations. The correct one is chosen by the compiler, not the programmer.

* * *

Page 28: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function Overloading

• The functions must differ in their parameter lists. The type and/or number of parameters must be different.

Examplesdouble myFunction(int, int, int);int myFunction(double, int, int);int myFunction (double, double);void myFunction(double);

*

Page 29: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Function Overloading

* * * *

.

// a is used// c is used// b is used// d is used

myFunction(3,4,5);myFunction(3.0, 4.0);myFunction(11.1, 9, 2);myFunction(23.56);{call

a double myFunction(int, int, int)b int myFunction(double, int, int)c int myFunction (double, double)d void myFunction(double)

}Header

Page 30: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Returning Values

• A function can receive many A function can receive many valuesvalues

• Only one value can be Only one value can be directlydirectly returned returned

Page 31: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Returning Values

• The returnreturn statement: tells the function which value to send back

to the calling program terminates the function call and returns

immediately to the calling program

Page 32: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Return Statement

• Syntax• return expression;

• Examples• return c;

• return hypotenuse;

Page 33: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Return Statement

• int find_max(int x, int y)• {

int maximum;

• if (x >= y)maximum = x;

elsemaximum = y;

• return maximum;}

same data type

*

Page 34: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Passing Data passing by value

gives a single value

passing by referencemay give back several valuesaccomplished by

using references (this topic)using pointers

*

Page 35: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

double Pythagorus(double a, double b){

double c;c = sqrt(a*a + b*b);return c;

}

Passing Data - by Value

• passing by value:A copycopy of a value is passed from the calling function to the called function.

* *

double Pythagorus(double a, double b){

a = a * a;b = b * b;double c = sqrt(a*a + b*b);return c;

}

Page 36: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

x

find_max(x, y)find_max(x, y)

arguments

y

* *

find_max(firstnum, secnum);find_max(firstnum, secnum);

call to find_maxcall to find_max

value in first_num is passed

865

value in sec_num is passed

9090

Storing Values into Parameters

Page 37: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

• void main(void)void main(void)• {{ double height = 4.0, base = 3.0;double height = 4.0, base = 3.0;• double Pythagorus(double, double);double Pythagorus(double, double);

• cout << “Hypotenuse = “cout << “Hypotenuse = “<< << PythagorusPythagorus((height, baseheight, base)<<endl;)<<endl;• . . .. . .

• }}

• double Pythagorus(double Pythagorus(double adouble a,, double b double b))• {{ double c;double c;

c = sqrt(a*a + b*b);c = sqrt(a*a + b*b);• return c;return c;• }}

Passing Data - by Value

* *

4.0 3.0

Page 38: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

• double Pythagorus(double a, double b)• { double c;

• a++;• b++;•

c = sqrt(a*a + b*b);• return c;• }

Passing Data - by Value

*

back in main: cout << height;cout << base:

4.0 3.0

Page 39: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Passing Data - by Value• void print_val(int); // function prototype

• void main(void)• { int w = 3;

• cout <<"w before the function call is "<<w<<‘\n’;• print_val(w);• cout <<"w after the function call is "<<w<<‘\n’;• }

• void print_val(int q)• { cout<<"Value passed to the function is "<<q<<endl;• q = q *2; // doubles the value• cout<<"Value at the end of the function is "<< q

<<endl;• }

Page 40: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Passing Data - by Value

• Output• w before the function call 3• Value passed to the function is 3• Value at the end of the function is 6• w after the function call is 3

Page 41: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Passing Data - by Reference

• Syntax

• double Pythagorus(double &&, double &&);

• Pythagorus(height, base);

• double Pythagorus(double& & a, double& & b)

function prototype

function call

function definition

Page 42: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

• void main(void)• { double height = 4.0, base = 3.0;• double Pythagorus(double &&, double &&);

• cout << “Hypotenuse = “ << Pythagorus(height, base) << endl;• . . .

• }

• double Pythagorus(double& & a, double& & b)• { double c;

c = sqrt(a*a + b*b);• return c;• }

Passing Data - by Reference

* *

addressaddress of heightof height

address address of baseof base

Page 43: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

• double Pythagorus(double& & a, double& & b)• { double c;

• a++;• b++;•

c = sqrt(a*a + b*b);• return c;• }

Passing Data - by Reference

*

addressaddress of heightof height

address address of baseof base

back in main: cout << height;cout << base:

Page 44: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Passing Data - by Reference• In main() values referenced as

1 value stored1 value stored

a

height

1 value stored1 value stored

b

base

In Pythagorus() values referenced as

*

Page 45: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Passing Data - by Reference• {• float a, b, c, sum, product;• void calc(float, float, float, float &, float &); // prototype• • cout << "Enter three numbers: ";• cin >> a >> b >> c;

• calc(a, b, c, sum, product); // call• cout << a<<“ + “<<b<<“ + “c<<“ = " << sum;• cout << ‘\n’<<a<<“ * “<<b<<“ * “c<<“ = " << product;• }

• void calc(float x, float y, float z, float &tot, float& multiply)• { tot = x + y + z; // definition• multiply = x * y * z;• x++; y++; z--; // for demo purposes• }

Page 46: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Passing Data - by Reference

• OutputEnter three numbers: 5 7 95 + 7 + 9 = 215 * 7 * 9 = 315

*

x is 6, y is 8, z is 8tot and sum refer to the same addressproduct and multiply refer to the same address

Page 47: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Passing Data - by Reference• void main(void)• { int w = 3;• void print_val(int &); // function prototype

• cout <<"w before the function call is "<<w<<‘\n’;• print_val(w);• cout <<"w after the function call is "<<w<<‘\n’;• }

• void print_val(int& q)• { cout<<"Value passed to the function is "<<q<<endl;• q = q *2; // doubles the value• cout<<"Value at the end of the function is "<< q

<<endl;• }

Page 48: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Passing Data - by Reference

• Output• w before the function call 3• Value passed to the function is 3• Value at the end of the function is 6• w after the function call is 6

Page 49: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Swap Routine

• void swap(float& num1, float& num2)• {• float temp;

• temp = num1;• num1 = num2;• num2 = temp;• }

Page 50: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Data Type Mismatch• value parameters

implicit type conversion - value of the actual parameter is coerced to the data type of the formal parameter

• reference parametersno coercion because an address is passed, not a value

* *

Page 51: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

A Comparison

• formal actual• parameter is parameter may be•

value variable, constant, or expression

type coercion may take place

• reference variable only• of exact same type as formal

Page 52: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

What’s Happening????

• call sequence

• 1. memory is allocated 2. parameters are passed3. transfer of control

return sequence

1. value of the return is stored 2. memory is deallocated3. transfer of control

* *

Page 53: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

FunctionsFunctions Data Flow Scope

local global

Global Resolution Operator part IIpart II

Page 54: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Data Flow

• Data flow is the direction of the information flow between the function and its caller.

• Adding data flow documentation to the function interface is helpful.

• The flow could be into a function, out of a function or both.

Page 55: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Parameter and Data Flow

pass data into a function /* in *//* in */

pass data out of a function /* out *//* out */

pass data into and out of a function /* inout *//* inout */

Page 56: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

• Examples

• void myFunction( /* in */ double nana, /* in */ int count)

• void yourFunction( /* out */ int& num1, /* out */ int& num2)

• void ourFunction( /* in */ int alpha, /* inout */ int& beta)

Parameter and Data FlowParameter and Data Flow

Page 57: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Parameter and Data FlowTo be certain a function does what you want

it to do, write value of variables as you enter and exit a function.

Put the output statement into a function and call it whenever you need it.

void ShowIt(void){ cout<< var1<< ‘\t’ <<var2<< ‘\t’ <<var3<< ‘\n’;}

*

Page 58: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Parameter and Data FlowFlow In

int media( /* in */ int cow){

cout << “Ten * cow = “ << cow*10;return (2*cow +5);

}

int media( /* in */ int cow){

cow = 2 * cow;return (2*cow +5);

}

&

out &

*

Page 59: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Parameter and Data Flow Flow Out

• void media( /* out */ float& delta,

• /* out */ float& epsilon )

• {

• delta = 1.0;

• epsilon = 0.0002;

• }

epsilon = epsilon - 0.0001;

*

inoutinout

epsilon = epsilon - 0.0001;epsilon = epsilon - 0.0001;

Page 60: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Parameter and Data Flow Flow In and Out

• void update( /* inout */ int& javel,

• /* inout */ int & grenelle )

• {

• javel = 3 * javel;

• grenelle++;

• }

Page 61: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Data Flow - Example• #include<iostream.h>

• void getTemp(double&);• void activity(double);• void convertCtoF(double&);

• void main(void)• {• double temperature;

• getTemp(temperature);• activity(temperature);• }

Page 62: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Data Flow - Example

• void getTemp(/* */ double& temp)• {{• cout<<"Enter the temperature in degrees C: ";• cin>> temp;• cout<<"The current temperature is "• <<temp<<" degrees celsius."<<endl;• convertCtoF(temp);• }}

• void convertCtoF( /* */ double& temp)• {{• temp=(1.8)*temp +32;• cout<<"This equals "<<temp• <<" degrees Fahrenheit."<<endl;• }}

out

inout

* *

Page 63: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Data Flow - Example

• void activity(/* */ double temp)• {{• cout<<"The recommended activity is ";• if(temp>85)• cout<<"swimming."<<endl;• else if(temp>70)• cout<<"tennis."<<endl;• else if(temp>35)• cout<<"golf."<<endl;• else if(temp>10)• cout<<"skiing."<<endl;• else• cout<<"dancing."<<endl;• }}

in

*

Page 64: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Data Flow

• data flowdata flow parameter-passingparameter-passingfor a parameterfor a parameter mechanismmechanism

• incoming pass-by-value

• outgoing pass-by-reference

• incoming/outgoing pass-by-reference

Page 65: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

I/O Example• void main(void)• {• 1 int red, blue;

• 2 void Mix( int&, int ); // prototype• 3 int Blend( int, int ); // prototype

• 4 red = 5;• 5 blue = Blend(3, red + 1);• 6 Mix(red, blue);• 7 cout << red << ' ' << blue << '\n';• 8 Mix(red, blue + red);• 9 cout << red << ' ' << blue << '\n';• 10 Mix(red, Blend(blue, red));• 11 cout << red << ' ' << blue << '\n';• }

Page 66: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

I/O Example• M void Mix( int& green, int yellow)• {• M1 int purple;• M2 cout << “enter Mix “ << green << ‘ ‘• << yellow << ‘\n’;• M3 purple = green + yellow;• M4 yellow = purple + yellow;• M5 green = purple;• M6 cout << “leav Mix “ << green << ‘ ‘ • << yellow << ‘\n’;• }

Page 67: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

I/O Example

• B int Blend( int red, int green )• {• B1 int yellow;

• B2 cout << “enter Blend “ << red <<‘ ‘ • << green << ‘\n’;• B3 yellow = red + green;• B4 cout << “leave Blend “ << red <<‘ ‘ • << green << ‘\n’;• B5 return (yellow + 1);• }

Page 68: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

• void Mix( /* ______ */ int& green,

• /* ______ */ int yellow )

• int Blend( /* ______ */ int red,

• /* ______ */ int green )

I/O Example

inout

in

in

in

* * * *

Page 69: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

• 1 2 3 4 5B B1 - B5

• 6M M1 - M6

I/O Example

* * * *

7 8 M M1 - M6

9 10M B B1 - B5 M1 - M6

11

The lines are executed in this order.

Page 70: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

I/O Example

• Mix memory Main

• green red

• blue

• yellow

• purplepurple

Page 71: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

© 2000 Scott S Albert

Mix Blend

Main

enter Blend 3 6leave Blend 3 6enter Mix 5 10leave Mix 15 2515 10enter Mix 15 25leave Mix 40 6540 10enter Blend 10 40leave Blend 10 40enter Mix 40 51leave Mix 91 14291 10

*

Page 72: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope

• A function is like a black box:You know what goes in and what comes out, but you do not know what happens inside the box.

Page 73: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope

• The section of the program where the variable is valid (known or visible).

• local = available to only one function

global = available several functions

Page 74: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope• Local:

The scope of an identifier declared inside a blockblock extends from the point of declaration to the end of that block.

• Global:The scope of an identifier declared outside all functions and classes extends from the point of declaration to the end of the source file.

* *

Page 75: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Local Variables declared within a function definition

private to a function definition

variables in different functions are totally independent

different functions can have variables with the same names; however, each variable will have its own memory address

* * * *

Page 76: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

• int x = 3;int x = 3; // global because before main

• void main(void)• { // no variables local to

main( )• void myfunction( ); // prototype

• cout <<"x = "<<x<<" before the function call.\n";• myfunction( );• cout <<"x = "<<x<<" after the function call.\n";• }

• void myfunction( )• {• int r; // local to myfunction( )• r = ++x;• cout <<"r = "<<r<<" within the function.\n";• }

Page 77: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope

• OUTPUT• x = 3 before the function call.• r = 4 within the function. • x = 4 after the function call.

Page 78: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Example - ReadValues

• void main(void)• { int a, b, c; float avg;

• void ReadValues( int&, int&, int& );• void Adjust( int&, int&, int& );• float Average( int, int, int );• void WriteResults( int, int, int, int,

float );

• ReadValues(a, b, c);• Adjust(a, b, c);• avg = Average(a, b, c);• WriteResults(a, b, c, a + b + c, avg);• }

1.

2.

3.

4.

5.

6.

7.

8.

9.

Page 79: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Example - ReadValues

• 1. main declares and calls ReadValues

• 2. ReadValues declares and calls ReadOne [3x]

• 3. main declares and calls Adjust

• 4. main declares and calls Average

• 5. main declares and calls WriteResults

* * * *

Page 80: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Example - ReadValues

• void ReadValues( /* */ int& x, /* */ int& y,

• /* */ int& z )• {• void ReadOne( char, int& );

• ReadOne('1', x );• ReadOne('2', y );• ReadOne('3', z );

• return;• }

* *

out

outout

Page 81: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Example - ReadOne

• void ReadOne( /* */ char number,• /* */ int& item )• {• cout << "Enter value " << number << ": ";• cin >> item;

• return;• }

* *

in

out

Page 82: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Example - Adjust

• void Adjust( /* */ int& i, /* */ int& j,• /* */ int& k )• {• int smallest;• smallest = i;

• if (j < smallest) i = i - smallest;• smallest = j; j = j - smallest;• if (k < smallest) k = k - smallest;• smallest = k; return;•

• }

* *

inoutinout

inout

Page 83: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Example - Average

• float Average( /* */ int item1, /* */ int item2, • /* */ int item3 )• {• int total;

• total = item1 + item2 + item3;• return float(total) / 3;• }

* *

in in

in

Page 84: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Example - WriteResults

• void WriteResults( /* */ int item1,• /* */ int item2, /* */ int item3,• /* */ int total, /* */ float average )• {• cout << "Adjusted values: " << item1 << ", " • << item2 << ", " << item3 << '\n'• << "Sum: " << total• << " Average: " << average << '\n';• return;• }

* *

in

ininin

in

Page 85: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

© 2000 Scott S Albert

ReadValues Adjust Average WriteResults

ReadOne

Main

Enter value 1: 23Enter value 2: 56Enter value 3: 78Adjusted values: 0, 33, 55Sum: 88 Average: 29.3333

Page 86: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

• void swap(int, int); // a globalglobal function

• void main(void)• { int x = 5, y = 10;

• 1. cout <<“Main-before swap, x: “<<x<<" y: "<<y<< '\n';• swap(x, y);• 2. cout <<"Main-after swap, x: "<<x<<" y: "<<y<<'\n';• }

• void swap(int x, int y)• { int temp;• 3. cout <<"Swap-before swap, x: "<<x<<" y: "<<y<<'\n';• temp = x;temp = x; x = y;x = y; y = temp;y = temp;• 4. cout <<"Swap-after swap, x: "<<x<<" y: "<<y<<'\n';• }

Page 87: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope

• OUTPUT

• 1. Main-before swap: x: 5 y: 10

• 3. Swap-before swap: x: 5 y: 10

• 4. Swap-after swap: x: 1010 y: 55

• 2. Main-after swap: x: 5 y: 10

Page 88: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

void Block1(int, char &);void Block2( );

int a1; // globalchar a2; // global

int main(){

. . .}

Scope within a Block

slide slide 1 1 of of 22

Page 89: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

• void Block1(int a1, char &b2) // prevents access• { // to global a1• int c1; // local to Block1• int d1; // local to Block1

• }

• }}

slide slide 2 2 of of 22 *

. . .

void Block2(){

int a1; // prevents access to global a1int b1; // local to Block2while (…){ // Block3// Block3

int c1; // local to Block3int b2; // prevents non-local access

}} // to b2 in Block1. . .

Page 90: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope within a block - Ex. 1predict the output

• void scope2(void); // function prototype

• void main(void)• { int v=100;int v=100;

• cout <<"v BEFORE function = "<<v<<'\n';• scope2();• cout <<"v AFTER function = "<<v<<'\n';• }

slide slide 1 1 of of 22

Page 91: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope within a block - Ex. 1predict the output

• 1. void scope2(void) //function header• 2. { double v = 5.5;• 3. int k, j;• 4. cout << "v outside block = " << v<<'\n';• 5. for (k=1; k<=3; k++)• 6. { int v = 17; // initialized in

function• 7. for (j=1; j<=2; j++)• 8. { v++;• 9. cout << "v inside block = " << v<<'\n';• 10. }• 11. }• 12. cout << "v outside block = " << v<<'\n'; • 13. }

slide slide 2 2 of of 22

Page 92: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope within a block - Ex. 2• void scope2(void); // function prototype

• void main(void)• { int v=100;int v=100;

• cout <<"v BEFORE function = "<<v<<'\n';• scope2();• cout <<"v AFTER function = "<<v<<'\n';• }

slide slide 1 1 of of 22

Page 93: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope within a block - Ex. 2

slide slide 2 2 of of 22

• 1. void scope2(void) //function header• 2. { double v = 5.5;• 3. int k, j;• 4. cout << "v outside block = " << v <<'\n';• 5. for (k=1; k<=3; k++)• 6. { int v = 17int v = 17; // initialized in

function• 7. for (j=1; j<=2; j++)• 8. { vv ++;• 9. cout << "v inside block = " << vv <<'\

n';• 10. }• 11. }• 12. cout << "v outside block = " << v <<'\n'; • }

Page 94: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope within a block

• OUTPUT• 100

BEFORE• 5.5 outside• 1818 insideinside• 1919 insideinside• 1818 insideinside• 1919 insideinside• 1818 insideinside• 1919 insideinside• 5.5 outside• 100

AFTERj loops

j loops}}}

*

Page 95: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Global Resolution Operator ::• double rougon = 999.99; // global

void main(void){

double rougon = 12.3; // localcout<< rougon << “ = rougon, local\n”cout<< ::::rougon << “ = rougon, global\n”;

}

• OUTPUTOUTPUT 12.3 = rougon, local 999.99 = rougon, global

* *

Page 96: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Variable Storage Classes

• Localautostaticregister

• while (){ int k = 1;

k++;

}

* * *

while (){ static int k = 1;

k++;

}

Page 97: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

• Global

static

extern •

Variable Storage Classes

Page 98: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope & Storage Classes - an example• int x = 1; // global variable

• main()• {• int x = 5; // local variable to main

• cout << "local x in outer scope of main is " << x << endl;

• { // start new scope• int x = 7;

• cout << "local x in inner scope of main is " <<x<< endl;• } // end new scope

• cout << "local x in outer scope of main is " << x << endl;

Page 99: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope & Storage Classes - an example• (continued) • a(); // a has automatic local x• b(); // b has static local x• c(); // c uses global x• a(); // a reinitializes automatic local x• b(); // static local x retains its previous value• c(); // global x also retains its value

• cout << "local x in main is " << x << endl;

• return 0;• } // end of main()

Page 100: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope & Storage Classes - an example

• void a(void)• {• int x = 25; // initialized each time a is called

• cout << endl << "local x in a is " << x • << " after entering a" << endl;• ++x;• cout << "local x in a is " << x • << " before exiting a" << endl;• }

Page 101: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope & Storage Classes - an example

• void b(void)• {• static int x = 50; // Static initialization only• // first time b is called• cout << endl << "local static x is " << x • << " on entering b" << endl;• ++x;• cout << "local static x is " << x • << " on exiting b" << endl;• }

Page 102: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope & Storage Classes - an example

• void c(void)• {• cout << endl << "global x is " << x • << " on entering c" << endl;• x *= 10;• cout << "global x is " << x << " on exiting c" <<

endl;• }

Page 103: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope & Storage Classes - an example

• a(); // a has automatic local x• b(); // b has static local x• c(); // c uses global x• a(); // a reinitializes automatic local x• b(); // static local x retains its previous

value• c(); // global x also retains its value

a(); b(); c();

*

Page 104: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope & Storage Classes - an example

• OUTPUT• local x in outer scope of main is 5• local x in inner scope of main is 7• local x in outer scope of main is 5

• local x in a is 25 after entering a• local x in a is 26 before exiting a

• local static x is 50 on entering b• local static x is 51 on exiting b

• global x is 1 on entering c• global x is 10 on exiting c

Page 105: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope & Storage Classes - an example

• local x in a is 25 after entering a• local x in a is 26 before exiting a

• local static x is 51 on entering b• local static x is 52 on exiting b

• global x is 10 on entering c• global x is 100 on exiting c• local x in main is 5

Page 106: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

Scope & Storage Classes - an example

• void a(void)• {• int x = 25; // initialized each time a is called

• cout << endl << "local x in a is " << x • << " after entering a" << endl;• ++x;• cout << "local x in a is " << x • << " before exiting a" << endl;• }

<< ‘\t’ << << ‘\t’ << ::::xx << endl;

*

Page 107: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

© 2000 Scott S Albert

Common Errors

Passing incorrect data typesPassing incorrect data types Using the same variable name for Using the same variable name for

different variablesdifferent variablesex. local - in both the calling andex. local - in both the calling and

called functions called functions

global - must use global - must use ::::

Page 108: Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I

© 2000 Scott S Albert

Common Errors

Wrong positioning of the called Wrong positioning of the called function prototypefunction prototype

Terminating a function header Terminating a function header with a with a ;;

Forgetting the data type of a Forgetting the data type of a function’s parameterfunction’s parameter