51
Chapter 6 Chapter 6 Functions Functions

Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Embed Size (px)

Citation preview

Page 1: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Chapter 6Chapter 6

FunctionsFunctions

Page 2: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

TopicsTopics• BasicsBasics• Simplest functionsSimplest functions• Functions receiving data from a callerFunctions receiving data from a caller• Default formal parameter valuesDefault formal parameter values• Functions sending data out to a callerFunctions sending data out to a caller• Function prototypesFunction prototypes• Overloading functionsOverloading functions• More on variables.More on variables.

Page 3: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Modular ProgrammingModular Programming

• Modular programmingModular programming: breaking a : breaking a program up into smaller, program up into smaller, manageable functions or modulesmanageable functions or modules

• FunctionFunction: a collection of statements : a collection of statements to perform a taskto perform a task

• Motivation for modular Motivation for modular programming:programming:– Improves maintainability of programsImproves maintainability of programs– Simplifies the process of writing Simplifies the process of writing

programsprograms

Page 4: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Defining and Calling Defining and Calling FunctionsFunctions

• Function callFunction call: statement causes a : statement causes a function to executefunction to execute

• Function definitionFunction definition: statements : statements that make up a functionthat make up a function

Page 5: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Function DefinitionFunction Definition

• Definition includes:Definition includes:– return type: data type of the value return type: data type of the value

that function returns to the part of the that function returns to the part of the program that called itprogram that called it

– name: name of the function. Function name: name of the function. Function names follow same rules as variablesnames follow same rules as variables

– parameter list: variables containing parameter list: variables containing values passed to the functionvalues passed to the function

– body: statements that perform the body: statements that perform the function’s task, enclosed in function’s task, enclosed in {}{}

Page 6: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Function Return TypeFunction Return Type

• If a function returns a value, the type If a function returns a value, the type of the value must be indicated:of the value must be indicated:

int main()int main()

• If a function does not return a value, its If a function does not return a value, its return type is return type is voidvoid::

void printHeading()void printHeading()

{{

cout << "\tMonthly Sales\cout << "\tMonthly Sales\n";n";

}}

Page 7: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Calling a FunctionCalling a Function

• To call a function, use the function To call a function, use the function name followed by name followed by ()() and and ;;printHeading();printHeading();

• When called, program executes When called, program executes the body of the called functionthe body of the called function

• After the function terminates, After the function terminates, execution resumes in the calling execution resumes in the calling function at point of call.function at point of call.

Page 8: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Calling FunctionsCalling Functions

• mainmain can call any number of can call any number of functionsfunctions

• Functions can call other functionsFunctions can call other functions• Compiler must know the following Compiler must know the following

about a function before it is called:about a function before it is called:– namename– return typereturn type– number of parametersnumber of parameters– data type of each parameterdata type of each parameter

Page 9: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Function DocumentationFunction Documentation

Function definition should be Function definition should be preceded by comments that preceded by comments that indicateindicate– Purpose of the functionPurpose of the function– How it works, what it doesHow it works, what it does– Input values that it expects, if anyInput values that it expects, if any– Output that it produces, if anyOutput that it produces, if any– Values that it returns, if anyValues that it returns, if any

Page 10: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Function PrototypesFunction Prototypes

• Ways to notify the compiler about Ways to notify the compiler about a function before a call to the a function before a call to the function:function:– Place function definition before Place function definition before

calling function’s definitioncalling function’s definition– Use a Use a function prototypefunction prototype ( (function function

declarationdeclaration) – like the function ) – like the function definition without the bodydefinition without the body•Header: Header: void printHeading()void printHeading()•Prototype: Prototype: void printHeading();void printHeading();

Page 11: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Prototype NotesPrototype Notes

• Place prototypes near top of Place prototypes near top of program program

• Program must include either Program must include either prototype or full function definition prototype or full function definition before any call to the function – before any call to the function – compiler error otherwisecompiler error otherwise

• When using prototypes, can place When using prototypes, can place function definitions in any order in function definitions in any order in source filesource file

Page 12: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Example Example #include <iostream>#include <iostream>using namespace std;using namespace std;

//function declarations//function declarationsvoid first();void first();void second();void second();

int main()int main(){{

cout << “I am starting in function”cout << “I am starting in function” <<“main. \n”;<<“main. \n”;first();first();second();second();cout << “back in function main cout << “back in function main

again \n”;again \n”;return 0;return 0;

}}

//Definition of function first//Definition of function first//this function displays a message//this function displays a message

void first()void first(){{

cout << “I am now inside the”cout << “I am now inside the”

<< “function first \n”; << “function first \n”; }}

//Definition of function second//Definition of function second//this function displays a message//this function displays a message

void second()void second(){{

cout << “I am now inside the”cout << “I am now inside the”

<< “function second \n”; << “function second \n”;

}}

Page 13: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Sending Data into a FunctionSending Data into a Function

• Can pass values into a function at Can pass values into a function at time of call:time of call:c = sqrt(a*a + b*b);c = sqrt(a*a + b*b);

• Values passed to function are Values passed to function are argumentsarguments

• Variables in function that hold values Variables in function that hold values passed as arguments are passed as arguments are parametersparameters

Page 14: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Other Parameter Other Parameter TerminologyTerminology

• A parameter can also be called a A parameter can also be called a formal parameterformal parameter or a or a formal formal argumentargument

• An argument can also be called an An argument can also be called an actual parameteractual parameter or an or an actual actual argumentargument

Page 15: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Example Example #include <iostream>#include <iostream>using namespace std;using namespace std;

//function declarations//function declarationsvoid displayValue(int);void displayValue(int);

int main()int main(){{

cout << “I am passing 5 to ”cout << “I am passing 5 to ” <<“displayValue. \n”;<<“displayValue. \n”;displayValue(5);displayValue(5);cout << “Now I am back in”cout << “Now I am back in” << “function main \n”;<< “function main \n”;return 0;return 0;

}}

//Definition of function displayValue//Definition of function displayValue//it uses an integer parameter whose//it uses an integer parameter whose//value is displayed.//value is displayed.

void displayValue(int num)void displayValue(int num){{

cout << “the value is ”cout << “the value is ”

<<num<<endl;<<num<<endl;}}

Page 16: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Parameters, Prototypes, Parameters, Prototypes, and Function Headingsand Function Headings

• For each function argument,For each function argument,– the prototype must include the data type the prototype must include the data type

of each parameter in its of each parameter in its ()()– the header must include a declaration for the header must include a declaration for

each parameter in its each parameter in its ()()

void evenOrOdd(int); //prototypevoid evenOrOdd(int); //prototype

void evenOrOdd(int num) //headervoid evenOrOdd(int num) //header

evenOrOdd(val); //callevenOrOdd(val); //call

Page 17: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Function Call NotesFunction Call Notes

• Value of argument is copied into parameter Value of argument is copied into parameter when the function is calledwhen the function is called

• A parameter’s scope is the function which A parameter’s scope is the function which uses ituses it

• Function can have > 1 parameterFunction can have > 1 parameter• There must be a data type listed in the There must be a data type listed in the

prototype prototype ()() and an argument declaration in and an argument declaration in the function header the function header ()() for each parameter for each parameter

• Arguments will be promoted/demoted as Arguments will be promoted/demoted as necessary to match parametersnecessary to match parameters

Page 18: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Calling Functions with Calling Functions with Multiple ArgumentsMultiple Arguments

When calling a function with multiple When calling a function with multiple arguments:arguments:– the number of arguments in the call the number of arguments in the call

must match the prototype and definitionmust match the prototype and definition– the first argument will be used to the first argument will be used to

initialize the first parameter, the second initialize the first parameter, the second argument to initialize the second argument to initialize the second parameter, etc.parameter, etc.

Page 19: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

The The returnreturn Statement Statement

• Used to end execution of a functionUsed to end execution of a function• Can be placed anywhere in a functionCan be placed anywhere in a function

– Statements that follow the Statements that follow the returnreturn statement will not be executedstatement will not be executed

• Can be used to prevent abnormal Can be used to prevent abnormal termination of program termination of program

• Without a Without a returnreturn statement, the statement, the function ends at its last function ends at its last }}

Page 20: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Example Example #include <iostream>#include <iostream>using namespace std;using namespace std;

//function declarations//function declarationsvoid divide(double,double);void divide(double,double);

int main()int main(){{

double num1,num2;double num1,num2;

cout << “Enter two numbers cout << “Enter two numbers and I will divide ”and I will divide ”

<< “the first number by << “the first number by the second \n”;the second \n”;

cin >> num1 >> num2; cin >> num1 >> num2; divide ( num1, num2);divide ( num1, num2);return 0;return 0;

}}

//Definition of function divide//Definition of function divide//uses two parameters: arg1 and arg2. //uses two parameters: arg1 and arg2.

thethe// function divides arg1 by arg2 and // function divides arg1 by arg2 and

shows shows // the results. If arg2 is zero, the function// the results. If arg2 is zero, the function//returns//returns

void divide (double arg1, double arg2)void divide (double arg1, double arg2){{

If (arg2 == 0)If (arg2 == 0)

{{cout << “Sorry, I cannot divide by”cout << “Sorry, I cannot divide by”

<< “zero \n”;<< “zero \n”;

return;return;

}}

cout<< “the result is ” cout<< “the result is ”

<< (arg1/arg2) <<endl;<< (arg1/arg2) <<endl;

}}

Page 21: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Returning a Value From a Returning a Value From a FunctionFunction•returnreturn statement can be used to return statement can be used to return

a value from function to the point of calla value from function to the point of call• Prototype and definition must indicate Prototype and definition must indicate

data type of return value (not data type of return value (not voidvoid))• Calling function should use return value:Calling function should use return value:

– assign it to a variableassign it to a variable– send it to send it to coutcout– use it in an expressionuse it in an expression

Page 22: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Returning a Boolean ValueReturning a Boolean Value

• Function can return Function can return truetrue or or falsefalse

• Declare return type in function Declare return type in function prototype and heading as prototype and heading as boolbool

• Function body must contain Function body must contain returnreturn statement(s) that return statement(s) that return truetrue or or falsefalse

• Calling function can use return value Calling function can use return value in a relational expressionin a relational expression

Page 23: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Boolean Boolean returnreturn Example Examplebool validTest(int); // prototypebool validTest(int); // prototype

bool validTest(int test) // headerbool validTest(int test) // header{{int lScore = 0, hScore = 100;int lScore = 0, hScore = 100;if (test >= lScore && test <= hScore)if (test >= lScore && test <= hScore)

return true;return true;elseelse

return false;return false;}}

if (validTest(score)) {...} // callif (validTest(score)) {...} // call

Page 24: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Passing Data by ValuePassing Data by Value

• Pass by valuePass by value: when an argument is : when an argument is passed to a function, its value is passed to a function, its value is copied into the parameter. copied into the parameter.

• Changes to the parameter in the Changes to the parameter in the function do not affect the value of function do not affect the value of the argument the argument

Page 25: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Passing Information to Passing Information to Parameters by ValueParameters by Value• Example: Example: int val=5;int val=5;

evenOrOdd(val);evenOrOdd(val);

•evenOrOddevenOrOdd can change variable can change variable numnum, , but it will have no effect on variable but it will have no effect on variable valval

5val

argument incalling function

5num

parameter inevenOrOdd function

Page 26: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Example Example #include <iostream>#include <iostream>using namespace std;using namespace std;

//function declarations//function declarationsvoid changeThem(int,double);void changeThem(int,double);

int main()int main(){{

int whole=12;int whole=12;double real=3.5;double real=3.5;

cout << “the value of whole is ”cout << “the value of whole is ” << whole <<“\n”;<< whole <<“\n”;cout << “the value of real is ”cout << “the value of real is ” << real <<“\n”;<< real <<“\n”;changeThem ( whole, real);changeThem ( whole, real);cout << “Now, the value of whole is ”cout << “Now, the value of whole is ” << whole <<“\n”;<< whole <<“\n”;cout << “the value of real is ”cout << “the value of real is ” << real <<“\n”;<< real <<“\n”;return 0;return 0;

}}

//Definition of function changeThem//Definition of function changeThem//it uses I, an int parameter, and f, a//it uses I, an int parameter, and f, a// double, the values of i and f are// double, the values of i and f are// changed and displayed.// changed and displayed.

void changeThem(int i, double f)void changeThem(int i, double f){{

i=100;i=100;

f=24.5;f=24.5;

cout << “value of i is changed cout << “value of i is changed to”to”

<< i <<“\n”;<< i <<“\n”;

cout << “value of f is changed cout << “value of f is changed to”to”

<< f <<“\n”;<< f <<“\n”;

}}

Page 27: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Using Reference Variables Using Reference Variables as Parametersas Parameters

• Mechanism that allows a function to Mechanism that allows a function to work with the original argument from work with the original argument from the function call, not a copy of the the function call, not a copy of the argumentargument

• Allows the function to modify values Allows the function to modify values stored in the calling environmentstored in the calling environment

• Provides a way for the function to Provides a way for the function to ‘return’ > 1 value‘return’ > 1 value

Page 28: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Passing by ReferencePassing by Reference

• A A reference variablereference variable is an alias for is an alias for another variableanother variable

• Defined with an ampersand (Defined with an ampersand (&&))void getDimensions(int&, int&);void getDimensions(int&, int&);

• Changes to a reference variable are Changes to a reference variable are made to the variable it refers tomade to the variable it refers to

• Use reference variables to implement Use reference variables to implement passing parameters by referencepassing parameters by reference

Page 29: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Example Example #include <iostream>#include <iostream>using namespace std;using namespace std;

//function declarations//function declarationsvoid changeThem(int &,double &);void changeThem(int &,double &);

int main()int main(){{

int whole=12;int whole=12;double real=3.5;double real=3.5;

cout << “the value of whole is ”cout << “the value of whole is ” << whole <<“\n”;<< whole <<“\n”;cout << “the value of real is ”cout << “the value of real is ” << real <<“\n”;<< real <<“\n”;changeThem ( whole, real);changeThem ( whole, real);cout << “Now, the value of whole is ”cout << “Now, the value of whole is ” << whole <<“\n”;<< whole <<“\n”;cout << “the value of real is ”cout << “the value of real is ” << real <<“\n”;<< real <<“\n”;return 0;return 0;

}}

//Definition of function changeThem//Definition of function changeThem//it uses I, an int parameter, and f, a//it uses I, an int parameter, and f, a// double, the values of i and f are// double, the values of i and f are// changed and displayed.// changed and displayed.

void changeThem(int &i, double &f)void changeThem(int &i, double &f){{

i=100;i=100;

f=24.5;f=24.5;

cout << “value of i is changed cout << “value of i is changed to”to”

<< i <<“\n”;<< i <<“\n”;

cout << “value of f is changed cout << “value of f is changed to”to”

<< f <<“\n”;<< f <<“\n”;

}}

Page 30: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Pass by Reference - Pass by Reference - ExampleExamplevoid sqareIt(int &); //prototypevoid sqareIt(int &); //prototype

void squareIt(int &num)void squareIt(int &num)

{{

num *= num;num *= num;

}}

int localVar = 5;int localVar = 5;

squareIt(localVar); // now has 25squareIt(localVar); // now has 25

Page 31: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Reference Variable NotesReference Variable Notes

• Each reference parameter must contain Each reference parameter must contain &&• Space between type and Space between type and && is unimportant is unimportant• Must use Must use && in both prototype and header in both prototype and header• Argument passed to reference parameter Argument passed to reference parameter

must be a variable – cannot be an expression must be a variable – cannot be an expression or constantor constant

• Use when appropriate – don’t use when Use when appropriate – don’t use when argument should not be changed by argument should not be changed by function, or if function needs to return only 1 function, or if function needs to return only 1 valuevalue

Page 32: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Using Functions in Using Functions in Menu-Driven ProgramsMenu-Driven Programs

• Functions can be used Functions can be used – to implement user choices from menuto implement user choices from menu– to implement general-purpose tasks:to implement general-purpose tasks:

•Higher-level functions can call general-Higher-level functions can call general-purpose functions, minimizing the total purpose functions, minimizing the total number of functionsnumber of functions and speeding and speeding program development timeprogram development time

Page 33: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Default ArgumentsDefault Arguments

Default argumentDefault argument is passed automatically is passed automatically to a function if argument is missing on the to a function if argument is missing on the function callfunction call

• Must be a constant declared in prototype:Must be a constant declared in prototype:void evenOrOdd(int = 0);void evenOrOdd(int = 0);

• Can be declared in header if no prototypeCan be declared in header if no prototype• Multi-parameter functions may have Multi-parameter functions may have

default arguments for some or all of them:default arguments for some or all of them:int getSum(int, int=0, int=0);int getSum(int, int=0, int=0);

Page 34: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Default argumentsDefault arguments

• void showArea (double = 20.0, double = 10.0);void showArea (double = 20.0, double = 10.0);

• void showArea (double length= 20.0, double void showArea (double length= 20.0, double width= 10.0);width= 10.0);

void showArea (double length, double width)void showArea (double length, double width)

{{double area=length*width;double area=length*width;

cout << “The area is ” <<area << endl;cout << “The area is ” <<area << endl;

}}

Page 35: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Default argumentsDefault arguments

void showArea (double length = 20.0, void showArea (double length = 20.0, double width = 10.0)double width = 10.0)

{{double area=length*width;double area=length*width;

cout << “The area is ” <<area << endl;cout << “The area is ” <<area << endl;

}}

Page 36: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Example Example #include <iostream>#include <iostream>using namespace std;using namespace std;

//function declarations//function declarationsvoid displayStars(int =10, int = void displayStars(int =10, int =

1);1);

int main()int main(){{

displayStar();displayStar();cout<<endl;cout<<endl;displayStar(5);displayStar(5);cout<<endl;cout<<endl;displayStar(7,3);displayStar(7,3);return 0;return 0;

}}

//Definition of function displayStar.//Definition of function displayStar.//the default argument for cols is 10 //the default argument for cols is 10

andand// for rows is 1, this function displays // for rows is 1, this function displays

a a // square made of asterisks// square made of asterisks

void displayStars(int cols, int rows);void displayStars(int cols, int rows);{{

for (int i=0, i < rows; i++)for (int i=0, i < rows; i++)

{{

for (int j=0, j < cols; j++)for (int j=0, j < cols; j++)

count << “*”;count << “*”;

count << endl;count << endl;

} }

}}

Page 37: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Default argumentsDefault arguments

• If not all parameters to a function have default values, the If not all parameters to a function have default values, the defaultless ones are declared first in the parameter list:defaultless ones are declared first in the parameter list:int getSum(int, int=0, int=0);int getSum(int, int=0, int=0);int getSum(int num1, int num2,int num3)int getSum(int num1, int num2,int num3){{

int sum;int sum;

sum = num1+num2+num3;sum = num1+num2+num3;cout << “the sum of three number is ”<<sum<<endl;cout << “the sum of three number is ”<<sum<<endl;return sum; return sum;

}}

int getSum(int, int=0, int);// int getSum(int, int=0, int);// int getSum(int=0, int, int);//int getSum(int=0, int, int);//

Page 38: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Local variable vs. Global Local variable vs. Global VarialbeVarialbe

• The general structure of a program:The general structure of a program:......TypeType11 function function11(…)(…) {…}{…}......TypeTypenn function functionn n (…)(…)

{…}{…}

int main ()int main () {…}{…}

Page 39: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

ExampleExample#include <iostream>#include <iostream>using namespace std;using namespace std;

void anotherFunction();void anotherFunction();

int main()int main(){{

int num=1;int num=1;

cout<<"in main, num is "<<num<<endl;cout<<"in main, num is "<<num<<endl;anotherFunction();anotherFunction();cout<<"back in main, num is "<<num<<endl;cout<<"back in main, num is "<<num<<endl;return 0;return 0;

}}

void anotherFunction()void anotherFunction(){{

int num=20;int num=20;

cout<<"in anotherFunction, num is "<<num<<endl;cout<<"in anotherFunction, num is "<<num<<endl;}}

Page 40: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Local and Global VariablesLocal and Global Variables

• local variablelocal variable: defined within a function : defined within a function or block, accessible only within the or block, accessible only within the function or blockfunction or block

• Other functions and blocks can define Other functions and blocks can define variables with the same namevariables with the same name

• When a function is called, local variables When a function is called, local variables in the calling function are not accessible in the calling function are not accessible from within the called functionfrom within the called function

Page 41: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Local and Global VariablesLocal and Global Variables

• global variableglobal variable: defined outside all : defined outside all functions, accessible to all functions functions, accessible to all functions within its scopewithin its scope

• Easy way to share large amounts of Easy way to share large amounts of data between functionsdata between functions

• Scope of a global variable: program Scope of a global variable: program from point of definition to the endfrom point of definition to the end

• Use sparinglyUse sparingly

Page 42: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

ExampleExample#include <iostream>#include <iostream>using namespace std;using namespace std;

void anotherFunction();void anotherFunction();int num=1;int num=1;

int main()int main(){{

cout<<"in main, num is "<<num<<endl;cout<<"in main, num is "<<num<<endl;anotherFunction();anotherFunction();

num=70;num=70;cout<<"back in main, num is "<<num<<endl;cout<<"back in main, num is "<<num<<endl;return 0;return 0;

}}

void anotherFunction()void anotherFunction(){{ cout<<"in anotherFunction, num is "<<num<<endl;cout<<"in anotherFunction, num is "<<num<<endl;

num=20;num=20;cout<<"in anotherFunction, num is "<<num<<endl;cout<<"in anotherFunction, num is "<<num<<endl;

}}

Page 43: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Initializing Local and Global Initializing Local and Global VariablesVariables• Local variables must be initialized by Local variables must be initialized by

programmerprogrammer

• Global variables are initialized to Global variables are initialized to 00 (numeric) or (numeric) or NULLNULL (character) when (character) when variable is definedvariable is defined

Page 44: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Local and Global Variable Local and Global Variable NamesNames• Local variables can have same Local variables can have same

names as global variablesnames as global variables

• When a function contains a local When a function contains a local variable that has the same name as variable that has the same name as a global variable, the global variable a global variable, the global variable is unavailable from within the is unavailable from within the function. The local definition “hides” function. The local definition “hides” the global definitionthe global definition

Page 45: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

#include <iostream>#include <iostream>using namespace std;using namespace std;

void springfield();void springfield();void QinDao();void QinDao();

int students=20000;int students=20000;

int main()int main(){{

cout<<“there are "<<students<<“ students”<<endl;cout<<“there are "<<students<<“ students”<<endl;springfield();springfield();

void QinDao();void QinDao();cout<<"back in main, students "<<students<<endl;cout<<"back in main, students "<<students<<endl;return 0;return 0;

}}

void springfield()void springfield(){{ int students=19000; int students=19000; cout<<"in springfield, "<<students<<endl;cout<<"in springfield, "<<students<<endl;}}

void QinDao()void QinDao(){{ int students=1000; int students=1000; cout<<"in QinDao, "<<students<<endl;cout<<"in QinDao, "<<students<<endl;}}

Page 46: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Static Local VariablesStatic Local Variables

• Local variables only exist while function Local variables only exist while function is executing. When function terminates, is executing. When function terminates, contents of local variables are lostcontents of local variables are lost

•staticstatic local variables retain their local variables retain their contents between function callscontents between function calls

•staticstatic local variables are defined and local variables are defined and initialized only the first time the function initialized only the first time the function is executed. is executed. 00 is default initialization is default initialization

Page 47: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Overloading FunctionsOverloading Functions

• Overloaded functionsOverloaded functions have the same have the same name but different parameter listsname but different parameter lists

• Can be used to create functions that Can be used to create functions that perform the same task but take different perform the same task but take different parameter types or different number of parameter types or different number of parametersparameters

• Compiler will determine which version of Compiler will determine which version of function to call by argument and function to call by argument and parameter listsparameter lists

Page 48: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Example Example #include <iostream>#include <iostream>using namespace std;using namespace std;

//function declarations//function declarationsint square(int);int square(int);double square(double);double square(double);

int main()int main(){{

int userInt;int userInt;double userDouble;double userDouble;cout << “Enter an integer and a double cout << “Enter an integer and a double

”” <<endl;<<endl;cin>>userInt>>userDouble;cin>>userInt>>userDouble;cout<<“Here are their squares: ”cout<<“Here are their squares: ”cout << square(userInt) <<“ and ”cout << square(userInt) <<“ and ” << square(userDouble);<< square(userDouble);return 0;return 0;

}}

int square(int number)int square(int number){{

return number * number;return number * number;}}

double square(double number)double square(double number){{

return number * number;return number * number;}}

Page 49: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Function Overloading Function Overloading ExamplesExamples

Using these overloaded functions,Using these overloaded functions,void getDimensions(int); // 1void getDimensions(int); // 1void getDimensions(int, int); // 2void getDimensions(int, int); // 2void getDimensions(int, double); // 3void getDimensions(int, double); // 3void getDimensions(double, double);// 4void getDimensions(double, double);// 4

the compiler will use them as follows:the compiler will use them as follows:int length, width; int length, width; double base, height;double base, height;getDimensions(length); // 1getDimensions(length); // 1getDimensions(length, width); // 2getDimensions(length, width); // 2getDimensions(length, height); // 3getDimensions(length, height); // 3getDimensions(height, base); // 4getDimensions(height, base); // 4

Page 50: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

The The exit()exit() Function Function

• Terminates execution of a programTerminates execution of a program• Can be called from any functionCan be called from any function• Can pass an Can pass an intint value to operating value to operating

system to indicate status of program system to indicate status of program terminationtermination

• Usually used for abnormal Usually used for abnormal termination of programtermination of program

• Requires Requires cstdlibcstdlib header file header file

Page 51: Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a

Stubs and DriversStubs and Drivers

• StubStub: dummy function in place of actual : dummy function in place of actual functionfunction

• Usually displays a message indicating it Usually displays a message indicating it was called. May also display parameterswas called. May also display parameters

• DriverDriver: a program that tests a function by : a program that tests a function by simply calling itsimply calling it

• Useful for testing and debugging Useful for testing and debugging program and function logic and designprogram and function logic and design