Sie sind auf Seite 1von 47

Functions

y A complex problem may be decomposed


into small or manageable parts or
ll d Functions
mod les called
modules

y main () itself is a function

y Function definition has a


y Name
y Parenthesis pair containing
zero or more parameters
y Body
y For each parameter there
should be a corresponding
d l
declaration
ti th t
that occurs
before the body
y
y Any parameter not declared is
taken
k as int
i b default
by d f lt

y General Format:
Format:
function type functionname (datatype argument1, datatype argument2....)
{
body of the function
------------------------
-------------------------
return something
}
y Declaration of Function Type:
y Function refers to the value it
would return to the calling portion
of the program

y e.g.
y int,
i t float,
fl t char,
h etct

y int function_name(…………
function_name(…………))
y float function_name(…………
function_name(…………))
y Function name :
y Name confirming to the syntax rules
of the variables

y Normally,
Normally function name is made
relevant with the function operation
y e.g.
y counter()
counter();;
y square()
square();;
y Formal Arguments:

y Any variable declared in the body of the


function is said to be local to the function

y Other variables which are not declared


either as arguments or in the function
body are Global to the function and are
defined externally
y Function
F i B d
Body

y After declaring the type of


function function name and
function,
formal arguments,
y A statement or a block off
statements is enclosed between
beginning and end
return statement
y Terminate the function and
return the value to its caller

y Itmay also be used to exit a


function without returning a
value
y The return statement may
or mayy not include an
expression
General Syntax
return;
return (expression);
Function Prototyping
y Prototype
yp describes the function interface
to the compiler by providing details such
as
y Number and type of arguments

y Type of return values


y With function prototyping, a template is
always
l used
d when
h declaring
d l i and d defining
d fi i a
function

y On callingg a function, the compiler


p uses
the template to ensure that proper
arguments are passed
y And the return value is treated correctly
y Any violation in matching of
arguments or of return types will be
caught by the compiler during compilation

y Function Prototype
y is a declaration statement in the
calling program and is of the
following form:
y type function-name (argument
function- argument- list));
-list
y Argument list consists of the types and
names off the
h arguments that
h must be b
passed to the function

y e.g.
g
y float volume(int x, float y, float z);

y Each variable must be declared


independently inside the parenthesis
y In a function declaration, names of the
arguments are dummy variables and
therefore they are optional

y i.e. the form


y float volume(int, float, float);
y is acceptable at the place of declaration

y At this stage the compiler checks only for


f
the type of arguments when the function
is called
ll d
y Variable names may be included or
excluded
l d d in
i the
h argument listli off
prototypes

y Variable names in the p


prototype
p jjust
act as place holders

y If names are used, they do not have to


match the names used in function call
or function definition
#include <iostream>
using namespace std;

void cheers (int); // prototype: No return value


d bl cube
double b (double
(d bl x);
) // prototype
t t : returns
t a double
d bl

int main(void)
{ // Start of main function
cheers (5); // function call
cout<<"Enter
cout<< Enter a Number:\n";
Number:\n ;
double side;
cin>>side;
double volume = cube(side); //function
//call

cout<<"A"<<side<<"foot cube has a


volume of";
cout<<volume<< cubic feet :\n
cout<<volume<<"cubic :\n";;
cheers(8);

system("pause");
return
t 0;
0
}// Main function finishes here
void cheers (int n)
{
for (int i=0; i<n;i++)
cout<<"Cheers!
cout<< Cheers! ";;
cout<<"\n";
}

double cube ((double x))


{
return x*x*x;;
}
Cheers! Cheers! Cheers! Cheers! Cheers!

Enter a Number:
2

A2foot cube has a volume of8cubic feet :

Cheers! Cheers! Cheers! Cheers! Cheers!


Cheers! Cheers! Cheers!
Press any key to continue . . .
#include <iostream>
using namespace std;

float cube (float x); // prototype

int main()
{ // Start of main function

cout<<"Enter length of side of a cube in


ft:\n";
float side;
cin side;
cin>>side;
float volume = cube(side); //function
call
cout<<"A"<<side<<"foot cube has a
volume ofof";;
cout<<volume<<"cubic feet :\n";

system("pause");
return 0;
}// Main function finishes here
float cube ((float y)
{
return y*y*y;
y y y;
}
Enter length of side of a cube in ft:
96
9.6
A9.6foot cube has a volume
of884.736cubic feet :
Press any key to continue . . .
y Till now all parameters have been passed
b value
by l

y Meaning
y Expression
p used in function call is
evaluated first
y Then the resulting value is passed on to
the corresponding parameter in the
function’ss parameter list
function
y Before function executes
y e.g.
y For cube(x) , with x having value 4
y 4 is ppassed to the local variable before
function execution starts

y x is unaffected by the function


y x is
i a read-
read l parameter
d-only t
y p
pass-by-value
y mechanism allows for
more general expressions to be used
instead of an actual p
parameter in the
function call

y e.g.
y cube(2*x-3)
cube(2*x 3)
y Expression inside the parentheses will be
evaluated to a single
g value and then the
value is passed to the function
Passing by Reference
y There are some situations where a
function needs to change the value of the
parameter p
p passed to it

y This is accomplished by passing it by


reference
y To pass by reference, simply append
an ampersand & to the type
specifier in the functions parameter
list

y This makes
Thi k th Local
the L l Variable
V i bl a
Reference to the actual parameter
passedd to
t it
y Actual parameter is read-write
instead of read-only
// Swapping

#include <iostream>
using namespace std;

void swap (float& x, float& y); // prototype

int main()
{ // Start of main function
fl t a=27.0;
float 27 0
float b=-5.041;

cout<<"a="<<a<<" "<<"b="<<b<<" "<<"\n";


swap(a,b);
cout<< \n ;
cout<<"\n";
cout<<"We are out of the function"<<"\n";
co t<<"\n"
cout<<"\n";
cout<<"swapping is over and the results
are: << \n ;
are:"<<"\n";
cout<<"\n";
cout<<"a="<<a<<"
cout<< a= <<a<< "<<"b="<<b<<"
<< b= <<b<< "<<"\n";
<< \n ;

system("pause");
t (" ")
return 0;
}// M
Main
i ffunction
ti fi finishes
i h here
h
void swap (float& x, float& y)
{
cout<<"\n"<<"We have stepped inside the
function"<<"\n";
cout<<"\n"<<"x="<<x<<"y="<<y<<"\n";
float temp=x;
x=y;
y=temp;
cout<<"Swapping
<<"S i isi over iinside
id the
h
function"<<"\n";
cout
cout<<"\n"<<"x="<<x<<"y="<<y<<"\n";
\n x x y y \n ;
return;
}
a=27 b=-5.041

We have stepped inside the function

x=27y=-5.041
27 5 041
Swapping is over inside the function

x=-5.041y=27

We are out of the function

swapping is over and the results are:

a=-5.041 b=27
Press any key to continue . . .
y The reference operator & makes x and y
y y of the actual parameters
synonyms p passed
p
to the function
Passing By Constant Reference
y If the actual p
parameter that is p
passed to a
function takes up a lot of storage space,

y Then it is more efficient to pass it by


reference to prevent it from being
duplicated
y This also allows the function to change
the value of the actual parameter
y However if the contents are not to be
changed
h d by
b the
h function,
f i then
h passing
i by
b
reference may be risky

y Alternative:
y passing by constant reference
y It works in the same way as passing by
reference,
f exceptt that
th t the
th function
f ti i
is
prevented from changing the value of the
parameter
t
y Effect is
Eff i that
h the
h function
f i h access to
has
the actual parameter by means of its
f
formall parameter alias,
li

y but the value of the formal parameter


may not be changed during the execution
of the function
// Passing by Constant Reference

#include <iostream>
using
sin namespace std;
std

void
id f(int
f(i t x, iint&
t& y, constt iint&
t& z);
)

iint main()
i ()
{ // Start of main function
int a=22, b=33,c=44;
cout<<"\n"<<" "<<"a="<<a<<" "<<"b="<<b<<" "<<"c="<<c<<"\n";
cout<<"\n"<<"Going inside the
f
function"<<"\n";
i "<<"\ "
f(a,b,c);
cout<<"\n"<<"We are out of the function"<<"\n";
cout<<"\n"<<" "<<"a="<<a<<" "<<"b="<<b<<" "<<"c="<<c<<"\n";

system("pause");
return 0;
}// Main function finishes here
void f(int x, int& y, const int& z)
{
cout<<"\n"<<"We have just entered into the function"<<"\n";
cout<<"\n"<<" "<<"x="<<x<<" "<<"y="<<y<<" "<<"z="<<z<<"\n";
x x z;
x=x+z;
y=y+z;
cout<<"\n"<<"Final Function Results at the last line of
function
function"<<"\n";
\n ;
cout<<"\n"<<" "<<"x="<<x<<" "<<"y="<<y<<" "<<"z="<<z<<"\n";
return;
}
a=22 b=33 c=44

Going inside the function

We have just entered into the function

x=22
x 22 y=33
y 33 z=44
z 44

Final Function Results at the last line of function

x=66 y=77 z=44

W are out off the


We h function
f i

a=22 b=77 c=44


Press any key to continue . . .
Default Arguments
y C++ allows
ll t callll a function
to f ti without
ith t
specifying its arguments

y The function assigns a default value to the


parameter which does not have a
matching argument in the function call

y Default values are specified when the


function is declared
y Compiler looks at the Prototype to see
how many arguments the function uses
y Alerts the program of the possible default
values
l

y e.g.
y float amount(float principal, int period, float rate=0.15);
y Argument rate has a default vale of 0.15
y value=amount(5000,7);

y Argument 5000 passes to principal, 7 to


period and rate uses a default value of
0.15

y Instead,,
y value = amount(5000,5,0.12);
y Rate is no more default but now is 0.12
0 12

Das könnte Ihnen auch gefallen