Ch2-Function
Ch2-Function
Function
Modularity
• Modular programming
– Breaking down the design of a program into individual
components (modules) that can be programmed and
tested independently
– A program divided into several smaller parts which
can interact
• Modules
– Can be written and tested separately
– Testing is easier (smaller)
– Doesn't need to be retested
– Reduces length of program
– Hides details (abstraction)
Functions in C++
• Modules in C++ are called functions
• Function - a subprogram that can act on data
and return a value
• Every C++ program has at least one function,
main(), where program execution begins
• A C++ program might contain more than one
function.
• Functions may interact using function call
• Functions in C++ come in two varieties:
– user-defined
– built-in
• E.g pow(), sqrt(), cin, etc
Declaration of Functions
• Functions must be declared before use
• The declaration tells the compiler
– The name,
– Return type,
– Parameters of the function
• Three ways
– Write your prototype into a file, and then use the
#include directive to include it in your program.
– Write the prototype into the file in which your function
is used.
– Define the function before it is called by any other
function.
Function Prototypes
• The declaration of a function is called its
prototype
• Is a statement - it ends with a semicolon
• It consists of the function's
– return type,
– name,
– parameter list
• Syntax
– return_type function_name (type
[parameterName1], type [ParameterName2] ... );
• E.g. long Area(int, int);
Or
long Area(int length, int width);
Function Prototypes
• All functions have a return type – default is int
• If the function doesn’t have a return type void
will be used
– void is a reserved word
• The function prototype usually placed at the
beginning of the program
• The definition of the prototype must be given
• Many of the built-in functions have their
function prototypes already written in the
header files you include in your program by
using #include
Defining a Function
• The definition tells the compiler how the function
works.
• Consists of :
– the function header :
• like the function prototype except that the parameters must be
named
• there is no terminating semicolon
– its body
• the task of the function
• Syntax
return_type function_name(parameter
declarations)
{
declarations;
statements;
}
Defining a Function
• E.g.
long Area(long l, long w)
{
return l * w;
}
• The return statement without any value is
typically used to exit the function early
• C++ does not allow nested functions
– The definition of one function cannot be
included in the body of another function
• A function definition must agree in return
type and parameter list with its prototype
Defining a Function
• If the function returns a value, it’s definition
should end with a return statement
• The body of the function is always enclosed in
braces, even when it consists of only one
statement
• return keyword
– Returns data, and control goes to function’s
caller
• If no data to return, use return;
– Function ends when reaches right brace
• Control goes to caller
// Creating and using a programmer-defined function.
#include <iostream.h>
Function prototype: specifies data types
int square( int ); // function prototype of arguments and return values.
square expects an int, and returns
int main() an int.
{
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function call
} // end main
1 4 9 16 25 36 49 64 81 100
Program Using a Function
#include <iostream.h>
double Celsius_to_Fahr(double); //Function Prototype
int main()
{
double temp,result;
cout<<“enter the temperature”<<endl;
cin>>temp;
result= Celsius_to_Fahr(temp);
cout<<“the corresponding Fahrenheit
is”<<result<<endl;
}
double Celsius_to_Fahr(double Celsius)
{
double temp; // Declare variables
temp = (9.0/5.0)*Celsius + 32; // Convert
return temp;
}
Execution of Functions
• Each function has its own name
• When that name is encountered, called
function call, the execution of the program
branches to the body of that function –
called function
• When the function returns, execution
resumes on the next line of the calling
function
• Functions can also call other functions and
can even call themselves
Scope of identifier
• Refers to where in the program an
identifier is accessible
• Determines how long it is available to your
program and where it can be accessed
• Two kind
– Local identifier - identifiers declared within a
function (or block)
– Global identifier – identifiers declared outside
of every function definition
Local scope
• You can declare variables within the body of the
function
– local variables
– When the function returns, the local variables are no
longer available
• Variables declared within a block are scoped to
that block – Local to that block
– they can be accessed only within that block and "go
out of existence" when that block ends
– E.g.
for(int i = 0;i<5; i++)
cout<<i;
i=+10; // compilation error i is inaccessible
Global Scope
• Variables defined outside of any function
have global scope
• Available from any function in the program,
including main()
• A local variable with the same name as a
global variable hides the global variable -
when used within the function
#include <iostream.h> void myFunction()
void myFunction(); // prototype {
int x = 5, y = 7; // global int y = 10;
variables
cout << "x from
int main() myFunction: " << x << "\
{ n";
cout << "x from main: " << x << cout << "y from
"\n"; myFunction: " << y << "\
cout << "y from main: " << y << n\n";
"\n\n";
}
myFunction();
cout << "Back from
Output: x from main: 5
myFunction!\n\n";
y from main: 7 x from myFunction: 5
cout << "x from main: " << x << y from myFunction: 10
"\n"; Back from myFunction!
cout << "y from main: " << y << x from main: 5
"\n"; y from main: 7
return 0;}
Global/Local Example
int count(0);
...
int main()
{
int x, y, z;
...
}
int calc(int a, int b)
{
int x;
count += x;
...
}
Unary Scope Resolution
Operator ::
• Using ::, one can access an global variable even
if it is over-shadowed by a local variable of the
same name.
• E.g.
#include <iostream.h>
float num=10.8;
int main(){
float num= 9.66;
cout<<the value of num is:<<::num<<endl;
return 0;
}
inline Functions
• Function calls
– Cause execution-time overhead
• Qualifier inline before function return type
"advises" a function to be inlined
• Puts copy of function's code in place of function call
– Speeds up performance but increases file size
– Compiler can ignore the inline qualifier
• Ignores all but the smallest functions
– E.g.
inline double cube( const double s )
{
return s * s * s;
}
inline functions
• Advantage: function call overhead is
eliminated, thus faster and less memory
consuming
• Disadvantage: the code is expanded
during compilation so that executable file
is large
Cont…
• #include <iostream>
• using namespace std;
• inline int Max(int x, int y)
• {
• return (x > y)? x : y;
• }
Cont…
{
cout << "Max (20,10): " << Max(20,10) <<
endl; cout << "Max (0,200): " <<
Max(0,200) << endl; cout << "Max
(100,1010): " << Max(100,1010) << endl;
return 0; }When the above code is
compiled and executed, it produces the
following result:
• Max (20,10): 20 Max (0,200): 200 Max
(100,1010): 1010
Functions with Default Parameters
• When a function is called
– The number of actual and formal parameters
must be the same
• C++ relaxes this condition for functions with
default parameters
• You specify the value of a default
parameter when the function name appears
for the first time, such as in the prototype
Functions with Default Parameters
(continued)
• If you do not specify the value of a default parameter
– The default value is used
• All of the default parameters must be the rightmost
parameters of the function
• In a function call where the function has more than one
default parameter and a value to a default parameter is
not specified
– You must omit all of the arguments to its right
• Default values can be constants, global variables, or
function calls
• The caller has the option of specifying a value other than
the default for any default parameter
• You cannot assign a constant value as a default value to
a reference parameter
Empty Parameter Lists
• functions can take no arguments
• To declare that a function takes no
parameters:
– Write void or nothing in parentheses
• E.g
– void print1( void );
– void print2();
Parameter Passing
• Call by Value
– Value of the function argument passed to the
formal parameter of the function
– Copy of data passed to function
– Changes to copy do not change original
• Call by Reference
– Address of the function argument passed to the
formal parameter of the function
Call by Reference
• If a formal parameter is a reference parameter
– It receives the address of the corresponding actual
parameter
– A reference parameter stores the address of the
corresponding actual parameter
• During program execution to manipulate the data
– The address stored in the reference parameter directs it to
the memory space of the corresponding actual parameter
– A reference parameter receives the address of the actual
parameter
• Reference parameters can:
– Pass one or more values from a function
– Change the value of the actual parameter
Call by Reference
• Reference parameters are useful in three
situations:
– Returning more than one value
– Changing the actual parameter
– When passing the address would save
memory space and time
#include <iostream.h>
int squareByValue( int );
void squareByReference( int & );
int main()
{
int x = 2, z = 4;
cout << "x = " << x << " before squareByValue\n" << "Value returned by
squareByValue:" << squareByValue( x )<<endl
<< "x = " << x << " after squareByValue\n" << endl;
cout << "z =" << z << " before squareByReference" << endl;
squareByReference( z );
cout << "z = " << z << " after squareByReference" << endl;
return 0;
}
int squareByValue( int a )
{
return a *= a; // caller's argument not modified
}
void squareByReference( int &cRef )
{
cRef *= cRef; // caller's argument modified
}
Call by Value Example
/* Incorrect function to switch two values */
hold = a;
a = b;
b = hold;
return;
}
Call by Reference Example
/* Correct function to switch two values */
hold = a;
a = b;
b = hold;
return;
}
Recursion and Recursive Functions