C++ 7 Ganjil 2018-2019
C++ 7 Ganjil 2018-2019
Functions
Introduction
• Divide and conquer
– Construct a program from smaller pieces or components
– Each piece more manageable than the original program
• Functions
– Modularize a program
– Software reusability
• Call function multiple times
2003 Prentice Hall, Inc. All rights reserved.
3
Functions
• Function definitions
– Only written once
– Hidden from other functions
• Local variables
– Known only in the function in which they are defined
– All variables declared in function definitions are local
variables
Functions
Functions
• Function prototype
– Tells compiler argument type and return type of function
– int square( int );
• Function takes an int and returns an int
– Explained in more detail later
• Calling/invoking a function
– square(x);
– Parentheses an operator used to call function
• Pass argument x
• Function gets its own copy of arguments
– After finished, passes back result
Functions
• Function Definition
– Format for function definition
return-value-type function-name( parameter-list )
{
declarations and statements
}
Parameter list
– Comma separated list of arguments
• Data type needed for each argument
– If no arguments, use void or leave blank
Function Prototypes
– Definition
double maximum( double x, double y, double z )
{
…
return…
}
Function Definitions
• Example function
int square( int y )
{
return y * y;
}
Exa mple
Function Prototypes
– Definition
void maximum( void )
{
…
}
Function Definitions
• Example function
void square( int y )
{
cout<< y * y;
}
• Example function
void square(void)
{
int y;
cout<<“Input nilai y!”;
cin>>y;
cout<< y * y;
}
Scope Rules
• Scope
– Portion of program where identifier can be used
• File scope
– Defined outside a function known in all functions
• Function scope
– Can only be referenced inside defining function
Scope Rules
• Block scope
– Begins at declaration, ends at right brace }
• Can only be referenced in this range
– Local variables, function parameters
– static variables still have block scope
• Storage class separate from scope
fig03_12.cpp
local static x is 51 on entering useStaticLocal
local static x is 52 on exiting useStaticLocal
output (2 of 2)
local x in main is 5