user defined functions chapter 7 2 chapter topics void functions without parameters void functions...
TRANSCRIPT
User Defined FunctionsUser Defined Functions
Chapter 7Chapter 7Chapter 7Chapter 7
2
Chapter TopicsChapter Topics
Void Functions Without ParametersVoid Functions Without ParametersVoid Functions With ParametersVoid Functions With ParametersReference ParametersReference ParametersValue and Reference Parameters and Memory Value and Reference Parameters and Memory AllocationAllocationReference Parameters and Value-Returning Reference Parameters and Value-Returning FunctionsFunctionsScope of an IdentifierScope of an IdentifierSide Effects of Global VariablesSide Effects of Global VariablesStatic and Automatic VariablesStatic and Automatic VariablesFunction OverloadingFunction OverloadingFunctions with Default ParametersFunctions with Default Parameters
Void Functions Without ParametersVoid Functions Without ParametersVoid Functions With ParametersVoid Functions With ParametersReference ParametersReference ParametersValue and Reference Parameters and Memory Value and Reference Parameters and Memory AllocationAllocationReference Parameters and Value-Returning Reference Parameters and Value-Returning FunctionsFunctionsScope of an IdentifierScope of an IdentifierSide Effects of Global VariablesSide Effects of Global VariablesStatic and Automatic VariablesStatic and Automatic VariablesFunction OverloadingFunction OverloadingFunctions with Default ParametersFunctions with Default Parameters
3
Void FunctionsVoid Functions
Void functions do Void functions do notnot return a value return a valueThink of them as performing a taskThink of them as performing a task
They may or may not have parametersThey may or may not have parameters
They usually do not have a return They usually do not have a return statementstatement
Although a return can be used to exit a Although a return can be used to exit a functionfunction
Void functions do Void functions do notnot return a value return a valueThink of them as performing a taskThink of them as performing a task
They may or may not have parametersThey may or may not have parameters
They usually do not have a return They usually do not have a return statementstatement
Although a return can be used to exit a Although a return can be used to exit a functionfunction
4
Void Functions Void Functions WithoutWithout Parameters Parameters
Syntax for the declaration:Syntax for the declaration:void functionName (void)void functionName (void)
{{
statementsstatements
}}
Syntax for the call:Syntax for the call:functionName();functionName();
Syntax for the declaration:Syntax for the declaration:void functionName (void)void functionName (void)
{{
statementsstatements
}}
Syntax for the call:Syntax for the call:functionName();functionName();
voidvoid in the parameter list is optional
The parentheses in the call is required, even when there
are no parameters
5
Void Functions Void Functions WithoutWithout Parameters Parameters
Consider a Consider a program program which will print the following which will print the following pattern:pattern:
********************************************************************************************************************************* Go Team ******************** Go Team ******************************************************************************************************************************************** BEAT ETBU ******************* BEAT ETBU **********************************************************************************************************************************
Note Note The prototypeThe prototypeThe syntax of the declaration, the definitionThe syntax of the declaration, the definitionThe syntax of the callThe syntax of the call
Consider a Consider a program program which will print the following which will print the following pattern:pattern:
********************************************************************************************************************************* Go Team ******************** Go Team ******************************************************************************************************************************************** BEAT ETBU ******************* BEAT ETBU **********************************************************************************************************************************
Note Note The prototypeThe prototypeThe syntax of the declaration, the definitionThe syntax of the declaration, the definitionThe syntax of the callThe syntax of the call
6
Improving FunctionsImproving Functions
We need to communicate to the functions
We need to communicate to the functions
7
Improving FunctionsImproving Functions
Sending values to the functionswith value parameters.
Sending values to the functionswith value parameters.
8
Functions Functions WithWith Parameters Parameters
Make functions more versatileMake functions more versatile
Send to the function a value Send to the function a value tells it how many times to do somethingtells it how many times to do something
gives it a value to be used in some way gives it a value to be used in some way (printed, calculated, etc.)(printed, calculated, etc.)
Make functions more versatileMake functions more versatile
Send to the function a value Send to the function a value tells it how many times to do somethingtells it how many times to do something
gives it a value to be used in some way gives it a value to be used in some way (printed, calculated, etc.)(printed, calculated, etc.)
9
Function ParametersFunction ParametersFormal parameterFormal parameter
declared in the function heading declared in the function heading
Actual parameterActual parametervariable or expression listed in a call variable or expression listed in a call (invocation) of the function(invocation) of the function
Formal parameterFormal parameterdeclared in the function heading declared in the function heading
Actual parameterActual parametervariable or expression listed in a call variable or expression listed in a call (invocation) of the function(invocation) of the function
void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }
void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }
10
Function Call (Invocation)Function Call (Invocation)
Use the name of the function as if it is a Use the name of the function as if it is a statementstatement
When the program reaches that statement,When the program reaches that statement, Control is then transferred to the functionControl is then transferred to the function
Use the name of the function as if it is a Use the name of the function as if it is a statementstatement
When the program reaches that statement,When the program reaches that statement, Control is then transferred to the functionControl is then transferred to the function
void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }
void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }
11
Function DeclarationsFunction Declarations
Why the prototypes?Why the prototypes?
All identifiers (including function names) must be All identifiers (including function names) must be declared before they are useddeclared before they are used
Compiler must know about the functionCompiler must know about the function
Why the prototypes?Why the prototypes?
All identifiers (including function names) must be All identifiers (including function names) must be declared before they are useddeclared before they are used
Compiler must know about the functionCompiler must know about the function
void calculate_rates ( );void find_matching_records (char id[]);
void main ( ) { . . . calculate_rates ( ); find_matching_records (emp_id);
void calculate_rates ( );void find_matching_records (char id[]);
void main ( ) { . . . calculate_rates ( ); find_matching_records (emp_id);
ParametersParameters
Function nameFunction nameFunction typeFunction type
12
Function DeclarationsFunction Declarations
It is also legal to include the definition It is also legal to include the definition (body) of the function with the heading all (body) of the function with the heading all beforebefore main( ) main( )
It is also legal to include the definition It is also legal to include the definition (body) of the function with the heading all (body) of the function with the heading all beforebefore main( ) main( )
void print_summary (int total) { . . . cout << . . . } void main ( ) { . . . print_summary (rpt_total); revenue = rpt_total * .72675; . . . }
void print_summary (int total) { . . . cout << . . . } void main ( ) { . . . print_summary (rpt_total); revenue = rpt_total * .72675; . . . }
This takes care of informing thecompiler of what it needs
and defining the source code also
This takes care of informing thecompiler of what it needs
and defining the source code also
13
Syntax of the Parameter ListSyntax of the Parameter List
In parenthesesIn parentheses
For For eacheach parameter parameterspecify type then namespecify type then name
separate type-name pairs with commasseparate type-name pairs with commas
In parenthesesIn parentheses
For For eacheach parameter parameterspecify type then namespecify type then name
separate type-name pairs with commasseparate type-name pairs with commas
void print_max_value (int value_1, int value_2, int value_3) { . . . }
void print_max_value (int value_1, int value_2, int value_3) { . . . }
14
Value ParametersValue Parameters
Defn => a formal parameter that receives a Defn => a formal parameter that receives a copy of the contents of the corresponding copy of the contents of the corresponding actual parameteractual parameter
Defn => a formal parameter that receives a Defn => a formal parameter that receives a copy of the contents of the corresponding copy of the contents of the corresponding actual parameteractual parameter
void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }
void main ( ) { . . . print_summary (rpt_total); . . . } void print_summary (int total) { . . . cout << . . . }
17
15
Value ParameterValue Parameter
Acts much like an assignment of a value to a Acts much like an assignment of a value to a variablevariable
The formal parameter is considered The formal parameter is considered locallocal to the to the functionfunction
The actual parameter The actual parameter may be an may be an expression expression or a constantor a constant
Acts much like an assignment of a value to a Acts much like an assignment of a value to a variablevariable
The formal parameter is considered The formal parameter is considered locallocal to the to the functionfunction
The actual parameter The actual parameter may be an may be an expression expression or a constantor a constant
void main ( ) { print_summary (0.5*rpt_total); . . . print_summary (200); } void print_summary (int total) { . . . cout << . . . }
View example program
16
Value ParametersValue Parameters
Consider … When we change the contents Consider … When we change the contents of the value parameter in the function …of the value parameter in the function …
What (if anything) happens to the actual What (if anything) happens to the actual parameter?parameter?
Consider … When we change the contents Consider … When we change the contents of the value parameter in the function …of the value parameter in the function …
What (if anything) happens to the actual What (if anything) happens to the actual parameter?parameter?
No, nothing happens.The actual parameter remains unchanged
No, nothing happens.The actual parameter remains unchanged
17
Reference ParametersReference Parameters
What if we What if we wantedwanted the actual parameter to the actual parameter to change?change?
C++ allows us to do this with C++ allows us to do this with referencereference parameters.parameters.
What if we What if we wantedwanted the actual parameter to the actual parameter to change?change?
C++ allows us to do this with C++ allows us to do this with referencereference parameters.parameters.
What is different in thisversion of the function?What is different in thisversion of the function?
18
Reference ParametersReference Parameters
It would be helpful tobe able to have the functions
communicate back to thecalling module.
It would be helpful tobe able to have the functions
communicate back to thecalling module.
19
Reference ParametersReference Parameters
Reference Parameters providethat capability
Reference Parameters providethat capability
20
Reference ParametersReference Parameters
Use the ampersand Use the ampersand && between the parameter between the parameter type and the identifiertype and the identifier
What actually happens is that this causes the What actually happens is that this causes the addressaddress of the actual parameter to be sent to the of the actual parameter to be sent to the formal parameterformal parameter
Then anything that happens to the formal Then anything that happens to the formal parameter is happening to the actual parameterparameter is happening to the actual parameter
Use the ampersand Use the ampersand && between the parameter between the parameter type and the identifiertype and the identifier
What actually happens is that this causes the What actually happens is that this causes the addressaddress of the actual parameter to be sent to the of the actual parameter to be sent to the formal parameterformal parameter
Then anything that happens to the formal Then anything that happens to the formal parameter is happening to the actual parameterparameter is happening to the actual parameter
View example program
21
Contrast Value & Reference ParametersContrast Value & Reference Parameters
Receives copy of valueReceives copy of value
Actual parameter can be Actual parameter can be constant, variable, constant, variable, expressionexpression
Value travels one way Value travels one way only (in)only (in)
Exact match of types Exact match of types (formal & actual) not (formal & actual) not criticalcritical
Receives copy of valueReceives copy of value
Actual parameter can be Actual parameter can be constant, variable, constant, variable, expressionexpression
Value travels one way Value travels one way only (in)only (in)
Exact match of types Exact match of types (formal & actual) not (formal & actual) not criticalcritical
Receives address of Receives address of actual parameteractual parameter
Actual parameter Actual parameter mustmust be a be a variablevariable
Value can be thought of Value can be thought of as traveling as traveling both ways both ways (in and out)(in and out)
Formal & actual Formal & actual parameters parameters mustmust be of be of same typesame type
Receives address of Receives address of actual parameteractual parameter
Actual parameter Actual parameter mustmust be a be a variablevariable
Value can be thought of Value can be thought of as traveling as traveling both ways both ways (in and out)(in and out)
Formal & actual Formal & actual parameters parameters mustmust be of be of same typesame type
ValueValue ReferenceReference
22
Reference ParametersReference Parameters
5 10
5
Recall our previous model for a function with Recall our previous model for a function with value parametersvalue parameters(values go in only)(values go in only)
Now consider a new version for Now consider a new version for referencereference parametersparametersValues go bothValues go bothin & outin & out
Recall our previous model for a function with Recall our previous model for a function with value parametersvalue parameters(values go in only)(values go in only)
Now consider a new version for Now consider a new version for referencereference parametersparametersValues go bothValues go bothin & outin & out
23Value and Reference Parameters Value and Reference Parameters and Memory Allocationand Memory Allocation
When a function is called, When a function is called, Memory for its formal parameters and Memory for its formal parameters and local local
variablesvariables is allocated in the function data is allocated in the function data area. area.
In the case of a value parameter, In the case of a value parameter, The value of the The value of the actual parameteractual parameter is copied is copied
into the memory cell of its corresponding into the memory cell of its corresponding formal parameterformal parameter..
When a function is called, When a function is called, Memory for its formal parameters and Memory for its formal parameters and local local
variablesvariables is allocated in the function data is allocated in the function data area. area.
In the case of a value parameter, In the case of a value parameter, The value of the The value of the actual parameteractual parameter is copied is copied
into the memory cell of its corresponding into the memory cell of its corresponding formal parameterformal parameter..
24Value and Reference Parameters Value and Reference Parameters and Memory Allocationand Memory Allocation
In the case of a reference parameter, In the case of a reference parameter, The The addressaddress of the actual parameter passes to the of the actual parameter passes to the
formal parameter. formal parameter.
Content of the formal parameter is an address.Content of the formal parameter is an address.
During execution, During execution, changes made to the changes made to the formal parameterformal parameter changechange the the
value of the value of the actual parameteractual parameter..
Stream variables (for example, Stream variables (for example, ifstream ifstream and and
ofstreamofstream) should be ) should be passed by referencepassed by reference
In the case of a reference parameter, In the case of a reference parameter, The The addressaddress of the actual parameter passes to the of the actual parameter passes to the
formal parameter. formal parameter.
Content of the formal parameter is an address.Content of the formal parameter is an address.
During execution, During execution, changes made to the changes made to the formal parameterformal parameter changechange the the
value of the value of the actual parameteractual parameter..
Stream variables (for example, Stream variables (for example, ifstream ifstream and and
ofstreamofstream) should be ) should be passed by referencepassed by reference
25Value and Reference Parameters Value and Reference Parameters and Memory Allocationand Memory Allocation
Note Note Example Program 7-6Example Program 7-6
Before function is called, this is the Before function is called, this is the memory picturememory picture
Note Note Example Program 7-6Example Program 7-6
Before function is called, this is the Before function is called, this is the memory picturememory picture
26Value and Reference Parameters Value and Reference Parameters and Memory Allocationand Memory Allocation
Once the flow of control is inside function Once the flow of control is inside function funOnefunOne( ),( ), this is the memory picture:this is the memory picture:Once the flow of control is inside function Once the flow of control is inside function funOnefunOne( ),( ), this is the memory picture:this is the memory picture:
Changes made to parameter bb will affect
num2num2 in main
27Value and Reference Parameters Value and Reference Parameters and Memory Allocationand Memory Allocation
Likewise, for function Likewise, for function funTwofunTwo( )( )
Changes made to Changes made to x x and and ww will affect will affect num2num2
and and chch, respectively, respectively
Likewise, for function Likewise, for function funTwofunTwo( )( )
Changes made to Changes made to x x and and ww will affect will affect num2num2
and and chch, respectively, respectively
Remember, this is because reference parameters hold addresses of the
actual parameters
28
Scope of IdentifiersScope of IdentifiersScope <=> the region of program code Scope <=> the region of program code where it is legal to reference (use) an where it is legal to reference (use) an identifieridentifier
LocalLocal scopescope <=> from where an identifier <=> from where an identifier is declared, on to the end of the blockis declared, on to the end of the block
Scope <=> the region of program code Scope <=> the region of program code where it is legal to reference (use) an where it is legal to reference (use) an identifieridentifier
LocalLocal scopescope <=> from where an identifier <=> from where an identifier is declared, on to the end of the blockis declared, on to the end of the block
void print_max_value (int value_1, int value_2, int value_3) { int hold_value; hold_value = value_1; if (value_2 > hold_value)
hold_value = value_2; . . . }
void print_max_value (int value_1, int value_2, int value_3) { int hold_value; hold_value = value_1; if (value_2 > hold_value)
hold_value = value_2; . . . }
BlockBlock
29
Scope of IdentifiersScope of Identifiers
Global (or file) scopeGlobal (or file) scopedeclared declared outsideoutside a block a block
from point of declaration on to end of entire filefrom point of declaration on to end of entire file
Global (or file) scopeGlobal (or file) scopedeclared declared outsideoutside a block a block
from point of declaration on to end of entire filefrom point of declaration on to end of entire file
int sum, count, n1, n2;void print_totals( int amt);void main ( ) { . . .
int sum, count, n1, n2;void print_totals( int amt);void main ( ) { . . . Rest of fileRest of file
30
Name PrecedenceName Precedence
Name of a local identifier can be the same as Name of a local identifier can be the same as the name of a global identifierthe name of a global identifier
Name precedence <=> local identifier has Name precedence <=> local identifier has precedence over precedence over global identifier global identifier with same namewith same name
Name of a local identifier can be the same as Name of a local identifier can be the same as the name of a global identifierthe name of a global identifier
Name precedence <=> local identifier has Name precedence <=> local identifier has precedence over precedence over global identifier global identifier with same namewith same name
void print_sum (int n1, int n2) { int sum; sum = n1 + n2; cout << sum; }
void main( ){ float sum, x, y; . . . print_sum (x, 34); . . .
void print_sum (int n1, int n2) { int sum; sum = n1 + n2; cout << sum; }
void main( ){ float sum, x, y; . . . print_sum (x, 34); . . .
31
Scope RulesScope Rules
How to decide where an identifier is How to decide where an identifier is accessibleaccessible
Look at where it is declaredLook at where it is declaredlocal (within a block)local (within a block)
global (within the file)global (within the file)
non-local (outside a given block)non-local (outside a given block)
Non local identifier may or may not be Non local identifier may or may not be accessibleaccessible
How to decide where an identifier is How to decide where an identifier is accessibleaccessible
Look at where it is declaredLook at where it is declaredlocal (within a block)local (within a block)
global (within the file)global (within the file)
non-local (outside a given block)non-local (outside a given block)
Non local identifier may or may not be Non local identifier may or may not be accessibleaccessible
32
Non-Local Accessible When ...Non-Local Accessible When ...
It is global and not same name as a local It is global and not same name as a local identifieridentifier
The location in question is nested within The location in question is nested within another block where the non local is another block where the non local is declareddeclared
It is global and not same name as a local It is global and not same name as a local identifieridentifier
The location in question is nested within The location in question is nested within another block where the non local is another block where the non local is declareddeclared
int x, y, z;void do_it (float x) { char y; . . . }void main ( ) { float y, z; . . . }
z
x
33
Scope RulesScope Rules
Function names are globalFunction names are globalno such thing as nested functionsno such thing as nested functions
Formal parameters considered local to the Formal parameters considered local to the functionfunction
Global identifiers have scopeGlobal identifiers have scopefrom definitionfrom definition
until end of fileuntil end of file
Local identifiers with same name as non-local Local identifiers with same name as non-local … local take precedence… local take precedence
Function names are globalFunction names are globalno such thing as nested functionsno such thing as nested functions
Formal parameters considered local to the Formal parameters considered local to the functionfunction
Global identifiers have scopeGlobal identifiers have scopefrom definitionfrom definition
until end of fileuntil end of file
Local identifiers with same name as non-local Local identifiers with same name as non-local … local take precedence… local take precedence
34
Side EffectsSide Effects
Any effect of one function on another that Any effect of one function on another that is is
not part of the explicitly defined interface not part of the explicitly defined interface between thembetween them
Caused byCaused bycareless use of reference parameterscareless use of reference parameters
poor design by use of globals in functionspoor design by use of globals in functions
Any effect of one function on another that Any effect of one function on another that is is
not part of the explicitly defined interface not part of the explicitly defined interface between thembetween them
Caused byCaused bycareless use of reference parameterscareless use of reference parameters
poor design by use of globals in functionspoor design by use of globals in functions
35
Globals in FunctionsGlobals in Functions
Assign value to globalsAssign value to globals
Call functionCall function
UseUse globalsglobals in function in function
Note -- accordingto the instructorthis is generallya bad practice!
36
Globals in FunctionsGlobals in Functions
This is a tempting way to goThis is a tempting way to goespecially when you don’t comprehend especially when you don’t comprehend parameters too well!!parameters too well!!
But it can cause unexpected problemsBut it can cause unexpected problemsTwo different functions can use the same Two different functions can use the same global (inadvertently)global (inadvertently)
All of a sudden get strange resultsAll of a sudden get strange results
This is a tempting way to goThis is a tempting way to goespecially when you don’t comprehend especially when you don’t comprehend parameters too well!!parameters too well!!
But it can cause unexpected problemsBut it can cause unexpected problemsTwo different functions can use the same Two different functions can use the same global (inadvertently)global (inadvertently)
All of a sudden get strange resultsAll of a sudden get strange results
SideEffects
37
Global ConstantsGlobal Constants
Value of a constant cannot be changedValue of a constant cannot be changed
Thus, acceptable to reference named Thus, acceptable to reference named constants globallyconstants globally
change of the constant can be done in the change of the constant can be done in the source code -- then recompilesource code -- then recompile
that change is then done for all instances of that change is then done for all instances of the identifierthe identifier
Value of a constant cannot be changedValue of a constant cannot be changed
Thus, acceptable to reference named Thus, acceptable to reference named constants globallyconstants globally
change of the constant can be done in the change of the constant can be done in the source code -- then recompilesource code -- then recompile
that change is then done for all instances of that change is then done for all instances of the identifierthe identifier
const int lines_per_page = 66;void main ( ) { . . .
38
Lifetime of a VariableLifetime of a Variable
Defn => Period of time during program Defn => Period of time during program execution when an identifier actually has execution when an identifier actually has memory allocated to itmemory allocated to it
Variables local toVariables local to a function not a function not allocated space allocated space until the program until the program enters the enters the functionfunction
Defn => Period of time during program Defn => Period of time during program execution when an identifier actually has execution when an identifier actually has memory allocated to itmemory allocated to it
Variables local toVariables local to a function not a function not allocated space allocated space until the program until the program enters the enters the functionfunction
void print_sum (int n1, int n2) { int sum; sum = n1 + n2; cout << sum; }
void main( ){ float sum, x, y; . . . print_sum (24, 34);
void print_sum (int n1, int n2) { int sum; sum = n1 + n2; cout << sum; }
void main( ){ float sum, x, y; . . . print_sum (24, 34);
De-allocatedwhen function
finishes
De-allocatedwhen function
finishes
39
int x=5, y;void do_it( ) { int a = 0; . . . }void to_it (float b ) { b = 3 ; . . . }void main ( ){ y = 17; do_it ( ); to_it ( ); cout << x + y;}
int x=5, y;void do_it( ) { int a = 0; . . . }void to_it (float b ) { b = 3 ; . . . }void main ( ){ y = 17; do_it ( ); to_it ( ); cout << x + y;}
Lifetime of a VariableLifetime of a Variable
O.S.
.exe code
x: 5y : 17GlobalsGlobals
LocalsLocals
Memory
40
int x=5, y;void do_it( ) { int a = 0; . . . }void to_it (float b ) { b = 3 ; . . . }void main ( ){ y = 17; do_it ( ); to_it ( ); cout << x + y;}
int x=5, y;void do_it( ) { int a = 0; . . . }void to_it (float b ) { b = 3 ; . . . }void main ( ){ y = 17; do_it ( ); to_it ( ); cout << x + y;}
Lifetime of a VariableLifetime of a Variable
O.S.
.exe code
x: 5y : 17GlobalsGlobals
a: 0
LocalsLocals
a allocated
Memory
41
int x=5, y;void do_it( ) { int a = 0; . . . }void to_it (float b ) { b = 3 ; . . . }void main ( ){ y = 17; do_it ( ); to_it ( ); cout << x + y;}
int x=5, y;void do_it( ) { int a = 0; . . . }void to_it (float b ) { b = 3 ; . . . }void main ( ){ y = 17; do_it ( ); to_it ( ); cout << x + y;}
Lifetime of a VariableLifetime of a Variable
O.S.
.exe code
x: 5y : 17GlobalsGlobals
LocalsLocals
a de-allocated
Memory
42
int x=5, y;void do_it( ) { int a = 0; . . . }void to_it (float b ) { b = 3 ; . . . }void main ( ){ y = 17; do_it ( ); to_it ( ); cout << x + y;}
int x=5, y;void do_it( ) { int a = 0; . . . }void to_it (float b ) { b = 3 ; . . . }void main ( ){ y = 17; do_it ( ); to_it ( ); cout << x + y;}
Lifetime of a VariableLifetime of a Variable
O.S.
.exe code
x: 5y : 17GlobalsGlobals
LocalsLocals
b : 2
b allocated
Memory
43
int x=5, y;void do_it( ) { int a = 0; . . . }void to_it (float b ) { b = 3 ; . . . }void main ( ){ y = 17; do_it ( ); to_it ( ); cout << x + y;}
int x=5, y;void do_it( ) { int a = 0; . . . }void to_it (float b ) { b = 3 ; . . . }void main ( ){ y = 17; do_it ( ); to_it ( ); cout << x + y;}
Lifetime of a VariableLifetime of a Variable
O.S.
.exe code
x: 5y : 17GlobalsGlobals
LocalsLocals
b de-allocated
44
Lifetime of a VariableLifetime of a Variable
Scope is a Scope is a compilecompile-time issue-time issue
Lifetime is a Lifetime is a runrun-time issue-time issue
Automatic variable Automatic variable allocated at block entryallocated at block entry
deallocated at exitdeallocated at exit
Static variableStatic variableonce allocated once allocated remainsremains allocated for whole allocated for whole programprogram
Scope is a Scope is a compilecompile-time issue-time issue
Lifetime is a Lifetime is a runrun-time issue-time issue
Automatic variable Automatic variable allocated at block entryallocated at block entry
deallocated at exitdeallocated at exit
Static variableStatic variableonce allocated once allocated remainsremains allocated for whole allocated for whole programprogram
45
Automatic vs. Static VariableAutomatic vs. Static Variable
storage for storage for automatic variable automatic variable is allocated at is allocated at block entry and block entry and deallocated at deallocated at block exitblock exit
storage for static storage for static variable remains variable remains allocated throughout allocated throughout execution of the execution of the entire programentire program
46
Static VariablesStatic Variables
By default, local variables are automatic.By default, local variables are automatic.
To obtain a static local variable, you To obtain a static local variable, you must use the reserved work must use the reserved work static static in in its declaration.its declaration.
47
StaticStatic and and AutomaticAutomatic Local VariablesLocal Variables
int popularSquare( int n)
{
static int timesCalled = 0 ; // initialized
// only once
int result = n * n ;
// initialized each time
timesCalled = timesCalled + 1 ;
cout << “Call # “ << timesCalled << endl ;
return result ;
}
int popularSquare( int n)
{
static int timesCalled = 0 ; // initialized
// only once
int result = n * n ;
// initialized each time
timesCalled = timesCalled + 1 ;
cout << “Call # “ << timesCalled << endl ;
return result ;
}
48
Static & Automatic VariablesStatic & Automatic Variables
What gets printed?What gets printed?
49
Function OverloadingFunction Overloading
In C++, you can have several functions In C++, you can have several functions with the same name. with the same name.
The compiler will consider them different if:The compiler will consider them different if:The number and/or type of parameters is The number and/or type of parameters is different and/or the type of the value returned different and/or the type of the value returned is differentis different
This is called the "signature" of a functionThis is called the "signature" of a function
C++ calls this overloading a function name.C++ calls this overloading a function name.
In C++, you can have several functions In C++, you can have several functions with the same name. with the same name.
The compiler will consider them different if:The compiler will consider them different if:The number and/or type of parameters is The number and/or type of parameters is different and/or the type of the value returned different and/or the type of the value returned is differentis different
This is called the "signature" of a functionThis is called the "signature" of a function
C++ calls this overloading a function name.C++ calls this overloading a function name.
50
Function OverloadingFunction Overloading
Instead of:Instead of:int largerInt(int x, int y);int largerInt(int x, int y);
char largerChar(char first, char second);char largerChar(char first, char second);
double largerDouble(double u, double v);double largerDouble(double u, double v);
string largerString(string first, string second);string largerString(string first, string second);
It is possible to overload a single function It is possible to overload a single function namenameint larger(int x, int y);int larger(int x, int y);
char larger(char first, char second);char larger(char first, char second);
double larger(double u, double v);double larger(double u, double v);
string larger(string first, string second);string larger(string first, string second);
Instead of:Instead of:int largerInt(int x, int y);int largerInt(int x, int y);
char largerChar(char first, char second);char largerChar(char first, char second);
double largerDouble(double u, double v);double largerDouble(double u, double v);
string largerString(string first, string second);string largerString(string first, string second);
It is possible to overload a single function It is possible to overload a single function namenameint larger(int x, int y);int larger(int x, int y);
char larger(char first, char second);char larger(char first, char second);
double larger(double u, double v);double larger(double u, double v);
string larger(string first, string second);string larger(string first, string second);
51
Functions with Default ParametersFunctions with Default Parameters
Normally when a function is called, Normally when a function is called, The number of actual and formal parameters The number of actual and formal parameters must be the same. must be the same.
C++ relaxes this condition for functions with C++ relaxes this condition for functions with default parametersdefault parameters. .
Default value for a parameter specified Default value for a parameter specified when the function name appears for the when the function name appears for the first timefirst time
In the prototypeIn the prototype
Or if whole definition appear before main()Or if whole definition appear before main()
Normally when a function is called, Normally when a function is called, The number of actual and formal parameters The number of actual and formal parameters must be the same. must be the same.
C++ relaxes this condition for functions with C++ relaxes this condition for functions with default parametersdefault parameters. .
Default value for a parameter specified Default value for a parameter specified when the function name appears for the when the function name appears for the first timefirst time
In the prototypeIn the prototype
Or if whole definition appear before main()Or if whole definition appear before main()
52
Functions with Default ParametersFunctions with Default Parameters
Example:Example:void doSomething (int x = 0, float y = 1.5);void doSomething (int x = 0, float y = 1.5);
Then the function can be called three Then the function can be called three different ways:different ways:
doSomething(6,12.99); doSomething(6,12.99);
// default values overridden// default values overridden
doSomething(4);doSomething(4);
// default int overridden// default int overridden
// default float of 1.5 is used// default float of 1.5 is used
doSomething();doSomething();
// both default values are used// both default values are used
Example:Example:void doSomething (int x = 0, float y = 1.5);void doSomething (int x = 0, float y = 1.5);
Then the function can be called three Then the function can be called three different ways:different ways:
doSomething(6,12.99); doSomething(6,12.99);
// default values overridden// default values overridden
doSomething(4);doSomething(4);
// default int overridden// default int overridden
// default float of 1.5 is used// default float of 1.5 is used
doSomething();doSomething();
// both default values are used// both default values are used