You are on page 1of 51

Chapter 3 - Functions

Outline 3.1 3.2 3.3 3. 3.! 3.$ 3.% 3.' 3.+ 3.10 3.11 3.12 3.13 3.1 3.1! Introduction Program Components in C++ Math Library Functions Functions Function "e#initions Function Prototypes &eader Files (andom )umber *eneration ,-ample. / *ame o# Chance and Introducing enum 1torage Classes 1cope (ules (ecursion ,-ample 2sing (ecursion. 3he Fibonacci 1eries (ecursion 4s. Iteration Functions 5ith ,mpty Parameter Lists

2000 Prentice Hall, Inc. All rights reserved.

Chapter 3 - Functions
Outline 3.1$ 3.1% 3.1' 3.1+ 3.20 3.21 Inline Functions (e#erences and (e#erence Parameters "e#ault /rguments 2nary 1cope (esolution Operator Function O4erloading Function 3emplates

2000 Prentice Hall, Inc. All rights reserved.

3.1 ivide and con!uer

Introduction

" Construct a progra# $ro# s#aller pieces or co#ponents " %ach piece #ore #anagea&le than the original progra#

2000 Prentice Hall, Inc. All rights reserved.

3.2 Program Components in C++ Progra#s (ritten &)


" co#&ining ne( $unctions (ith *prepac+aged, $unctions in the C-- standard li&rar). " .he standard li&rar) provides a rich collection o$ $unctions.

'

Functions are invo+ed &) a $unction call


" A $unction call speci$ies the $unction na#e and provides in$or#ation /as argu#ents0 that the called $unction needs " 1oss to (or+er analog)2
A boss (the calling function or caller) asks a worker (the called function) to perform a task and return (i.e., report back) the results when the task is done.

2000 Prentice Hall, Inc. All rights reserved.

3.2

Program Components in C++

Function de$initions
" 4nl) (ritten once " .hese state#ents are hidden $ro# other $unctions. " 1oss to (or+er analog)2
The boss does not know how the worker gets the job done; he just wants it done

2000 Prentice Hall, Inc. All rights reserved.

3.3

Math Library Functions

6ath li&rar) $unctions


" Allo( the progra##er to per$or# co##on #athe#atical calculations " Are used &) including the header $ile <cmath>

Functions called &) (riting


functionName /argument0

%7a#ple
cout << sqrt( 900.0 );

" Calls the sqrt /s!uare root0 $unction. .he preceding state#ent (ould print 30 " .he sqrt $unction ta+es an argu#ent o$ t)pe double and returns a result o$ t)pe double, as do all $unctions in the #ath li&rar)
2000 Prentice Hall, Inc. All rights reserved.

3.3
" Constants

Math Library Functions

Function argu#ents can &e


sqrt( 4 );

" 9aria&les
sqrt( x );

" %7pressions
sqrt( sqrt( x ) ) : sqrt( 3 - 6x );

2000 Prentice Hall, Inc. All rights reserved.

3. Functions

Functions

" Allo( the progra##er to #odulari<e a progra#

=ocal varia&les
" >no(n onl) in the $unction in (hich the) are de$ined " All varia&les declared in $unction de$initions are local varia&les

Para#eters
" =ocal varia&les passed (hen the $unction is called that provide the $unction (ith outside in$or#ation

2000 Prentice Hall, Inc. All rights reserved.

3.!

Function "e#initions

Create custo#i<ed $unctions to


" .a+e in data " Per$or# operations " @eturn the result

Format for function definition:


return-value-type function-name/ parameter-list 0 A declarations and statements B

%7a#ple2
int square( int y) return y ! y; "
2000 Prentice Hall, Inc. All rights reserved.

# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3

$$ %i&. 3.3' (i&03)03.c** $$ ,reatin& and usin& a *ro&rammer-de(ined (unction -include <iostream> usin& std''cout; usin& std''endl; int square( int ); int main() (or ( int x 1 #; x <1 #0; x22 ) cout << square( x ) << 3 3; cout << endl; return 0; " $$ %unction de(inition int square( int y ) return y ! y; "

Outline

10

1. Function prototype Cotice ho( para#eters and return value are declared.
$$ (unction *rototy*e

2. Loop 3. Function de#inition

#6

+.

36

49

64

0#

#00

Program Output

2000 Prentice Hall, Inc. All rights reserved.

# + 3 4 . 6 / 0 9 #0

$$ %i&. 3.4' (i&03)04.c** $$ %indin& the maximum o( three inte&ers -include <iostream>

Outline

11

1. Function prototype 63 parameters7 2. Input 4alues 2.1 Call #unction


$$ (unction *rototy*e

usin& std''cout; usin& std''cin; usin& std''endl;

int maximum( int4 int4 int );

## int main() #+ #3 #4 #. #6 #/ #0 #9 $$ a4 b and c belo6 are ar&uments to $$ the maximum (unction call cout << 35nter three inte&ers' 3; cin >> a >> b >> c; int a4 b4 c;

+0 2000 cout << 37aximum is' 3 reserved. << maximum( a4 b4 c ) << endl; Prentice Hall, Inc. All rights

+# ++ +3 +4 +. +6 +/ +0 +9 30 3# 3+ 33 34 3. 36 3/ 30 39

return 0; " $$ %unction maximum de(inition $$ x4 y and 8 belo6 are *arameters to $$ the maximum (unction de(inition int maximum( int x4 int y4 int 8 ) int max 1 x; i( ( y > max ) max 1 y; i( ( 8 > max ) max 1 8; return max; "

Outline

12

3. Function de#inition

5nter three inte&ers' ++ 0. #/ 7aximum is' 0. 5nter three inte&ers' 9+ 3. #4 7aximum is' 9+ 5nter three inte&ers' 4. #9 90 7aximum is' 90

Program Output

2000 Prentice Hall, Inc. All rights reserved.

3.$
" Function na#e " Para#eters

Function Prototypes

13

Function protot)pe
In$or#ation the $unction ta+es in

" @eturn t)pe


.)pe o$ in$or#ation the $unction passes &ac+ to caller /de$ault int0 9oid signi$ies the $unction returns nothing

" 4nl) needed i$ $unction de$inition co#es a$ter the $unction call in the progra#

%7a#ple2
int maximum( int4 int4 int );

" .a+es in 3 ints " @eturns an int


2000 Prentice Hall, Inc. All rights reserved.

3.% Header $iles

&eader Files

1'

" Contain $unction protot)pes $or li&rar) $unctions <cstdlib> , <cmath>, etc. " =oad (ith -include <(ilename>
%7a#ple2 -include <cmath>

Custo# header $iles


" e$ined &) the progra##er " Dave as (ilename.h " =oaded into progra# using
-include 3(ilename.h3

2000 Prentice Hall, Inc. All rights reserved.

3.'

(andom )umber *eneration

13

rand $unction
i 1 rand();

" =oad <cstdlib> " Eenerates a pseudorando# nu#&er &et(een 0 and :;<=)7;> /usuall) 328580
A pseudorando# nu#&er is a preset se!uence o$ Frando#F nu#&ers .he sa#e se!uence is generated upon ever) progra# e7ecution

srand $unction
" Gu#ps to a seeded location in a Frando#F se!uence
srand( seed ); srand( time( 0 ) ); $$must include <ctime>

time( 0 )
.he ti#e at (hich the progra# (as co#piled

" Changes the seed ever) ti#e the progra# is co#piled, there&) allo(ing rand to generate rando# nu#&ers
2000 Prentice Hall, Inc. All rights reserved.

3.' Dcaling

(andom )umber *eneration

15

" @educes rando# nu#&er to a certain range " 6odulus / ? 0 operator


@educes nu#&er &et(een 0 and :;<=)7;> to a nu#&er &et(een 0 and the scaling $actor

" %7a#ple
i 1 rand() ? 6 2 #; Eenerates a nu#&er &et(een # and 6

2000 Prentice Hall, Inc. All rights reserved.

# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3 +4

$$ %i&. 3./' (i&03)0/.c** $$ @hi(ted4 scaled inte&ers *roduced by # 2 rand() ? 6 -include <iostream> usin& std''cout; usin& std''endl; -include <iomani*> usin& std''set6; -include <cstdlib> int main() (or ( int i 1 #; i <1 +0; i22 ) cout << set6( #0 ) << ( # 2 rand() ? 6 ); i( ( i ? . 11 0 ) cout << endl; " return 0; "

Outline
1. "e#ine loop 2. Output random number

18

Cotice rand() ? 6 . .his returns a nu#&er &et(een 0 and 5 /scaling0. Add 1 to get a nu#&er &et(een # and 6.

%7ecuting the progra# again gives the sa#e Frando#F dice rolls.
. 4 3 # 3 + + 4 . . + 6 . . # 4

. + . .

Program Output

2000 Prentice Hall, Inc. All rights reserved.

# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3 +4 +. +6 +/ +0 +9 30 3#

$$ %i&. 3.9' (i&03)09.c** $$ :andomi8in& die-rollin& *ro&ram -include <iostream> usin& std''cout; usin& std''cin; usin& std''endl; -include <iomani*> usin& std''set6; -include <cstdlib> int main() unsi&ned seed; cout << 35nter seed' 3; cin >> seed; srand( seed ); (or ( int i 1 #; i <1 #0; i22 ) cout << set6( #0 ) << # 2 rand() ? 6; i( ( i ? . 11 0 ) cout << endl; "

Outline
1. Initiali8e seed

1;

2. Input 4alue #or seed 2.1 2se srand to change random se9uence 2.2 "e#ine Loop 3. *enerate and output random numbers

" 2000 Prentice Hall, Inc. All rights reserved.

return 0;

5nter seed' 6/ # . 5nter seed' 43+ 4 + 5nter seed' 6/ # .

6 6

. 3

# #

4 +

Outline
Program Output

1?

+ . 6 6

6 # . 3

4 4 # #

3 4 4 +

Cotice ho( the die rolls change (ith the seed.

2000 Prentice Hall, Inc. All rights reserved.

3.+

,-ample. / *ame o# Chance 20 and Introducing enum


enum typeName {constant , constant!};

%nu#eration - set o$ integers (ith identi$iers


" Constants start at 0 /de$ault0, incre#ented &) # " Hni!ue constant na#es " %7a#ple2
enum @tatus ,A<BC<D54 EA<4 FA@B";

Create an enu#eration varia&le o$ t)pe typeName


" 9aria&le is constant, its value #a) not &e reassigned
@tatus enumGar; enumGar 1 EA<; enumGar 1 #; $$ create 9ariable $$ set equal to EA< $$ 5::A:

2000 Prentice Hall, Inc. All rights reserved.

21 ,-ample. / *ame o# Chance and Introducing enum6II7

%nu#eration constants can have values pre-set


enum 7onths H;< 1 #4 %5I4 7;:4 ;J:4 7;K4 HD<4 HDF4 ;DL4 @5J4 A,B4 <AG4 =5,"; " Dtarts at #, incre#ents &) #

Craps si#ulator rules


" @oll t(o dice
8 or 11 on $irst thro(, pla)er (ins 2, 3, or 12 on $irst thro(, pla)er loses ', 3, 5, ;, ?, 10 " value &eco#es pla)erIs FpointF " pla)er #ust roll his point &e$ore rolling 8 to (in

2000 Prentice Hall, Inc. All rights reserved.

# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3 +4 +. +6 +/ +0 +9 30 3# 3+ 33 34

$$ %i&. 3.#0' (i&03)#0.c** $$ ,ra*s -include <iostream> usin& std''cout; usin& std''endl; -include <cstdlib> -include <ctime> usin& std''time; int roll=ice( 9oid ); int main() enum @tatus ,A<BC<D54 EA<4 FA@B "; int sum4 myJoint; @tatus &ame@tatus; srand( time( 0 ) ); sum 1 roll=ice(); $$ (unction *rototy*e

Outline

22

1. roll=ice prototype 1.1 Initiali8e 4ariables and enum 1.2 1eed srand 2. "e#ine s6itch statement #or 5in:loss:continue

Cotice ho( the enum is de$ined

$$ (irst roll o( the dice

s6itch ( sum ) case /' case ##' $$ 6in on (irst roll &ame@tatus 1 EA<; breaM; case +' case 3' case #+' $$ lose on (irst roll &ame@tatus 1 FA@B; breaM; 2000 Prentice Hall, Inc. All rights reserved.

3. 36 3/ 30 39 40 4# 4+ 43 44 4. 46 4/ 40 49 .0 .# .+ .3 .4 .. .6 ./ .0 " " "

de(ault' &ame@tatus 1 ,A<BC<D5; myJoint 1 sum;

$$ remember *oint

Outline
2.1 "e#ine loop to continue playing 2.2 Print 5in:loss

23

cout << 3Joint is 3 << myJoint << endl; breaM; $$ o*tional

6hile ( &ame@tatus 11 ,A<BC<D5 ) sum 1 roll=ice(); i( ( sum 11 myJoint ) &ame@tatus 1 EA<; else i( ( sum 11 / ) &ame@tatus 1 FA@B;

$$ Mee* rollin&

$$ 6in by maMin& *oint

$$ lose by rollin& /

i( ( &ame@tatus 11 EA< ) cout << 3Jlayer 6ins3 << endl; else cout << 3Jlayer loses3 << endl; return 0;

.9 2000 Prentice Hall, Inc. All rights reserved.

60 int roll=ice( 9oid ) 61 62 int die#4 die+4 6orM@um; 63 64 die# 1 # 2 rand() ? 6; 65 die+ 1 # 2 rand() ? 6; 66 6orM@um 1 die# 2 die+; 67 cout << 3Jlayer rolled 3 << die# << 3 2 3 << die+ 68 << 3 1 3 << 6orM@um << endl; 69 70 return 6orM@um; 71 " Jlayer rolled 6 2 . 1 ## Jlayer 6ins Jlayer rolled 6 2 . 1 ## Jlayer 6ins Jlayer rolled Joint is #0 Jlayer rolled Jlayer rolled Jlayer rolled Jlayer rolled Jlayer 6ins 4 2 6 1 #0 + 6 3 6 2 2 2 2 4 . 3 4 1 1 1 1 6 ## 6 #0

Outline
3. "e#ine roll=ice #unction

2'

Program Output

Jlayer rolled # 2 3 1 4 Joint is 4 Jlayer rolled # 2 4 1 . Jlayer rolled . 2 4 1 9 Jlayer rolled 4 2 6 1 #0 Jlayer rolled 6 2 3 1 9 Jlayer rolled # 2 + 1 3 Jlayer rolled . 2 + 1 / Jlayer loses 2000 Prentice Hall, Inc. All rights reserved.

3.10 1torage Classes Dtorage class speci$iers


" Dtorage class
Jhere o&Kect e7ists in #e#or)

23

" Dcope
Jhere o&Kect is re$erenced in progra#

" =in+age
Jhere an identi$ier is +no(n

Auto#atic storage
" 4&Kect created and destro)ed (ithin its &loc+ auto
e$ault $or local varia&les. %7a#ple2 auto (loat x4 y;

re&ister
Tries to put variables into high-speed registers

Can only be used with local variables and parameters


2000 Prentice Hall, Inc. All rights reserved.

3.10 1torage Classes Dtatic storage


" 9aria&les e7ist $or entire progra# e7ecution
static

25

=ocal varia&les de$ined in $unctions >eep value a$ter $unction ends 4nl) +no(n in their o(n $unction

5xtern
e$ault $or glo&al varia&les and $unctions. >no(n in an) $unction

2000 Prentice Hall, Inc. All rights reserved.

3.11 Identi#ier 1cope (ules File scope

28

" e$ined outside a $unction, +no(n in all $unctions " %7a#ples include, glo&al varia&les, $unction de$initions and $unctions protot)pes

Function scope
" Can onl) &e re$erenced inside a $unction &od) " 4nl) la&els /start', case', etc.0

1loc+ scope
" eclared inside a &loc+. 1egins at declaration, ends at B " 9aria&les, $unction para#eters /local varia&les o$ $unction0 " 4uter &loc+s *hidden, $ro# inner &loc+s i$ sa#e varia&le na#e

Function protot)pe scope


" Identi$iers in para#eter list " Ca#es in $unction protot)pe optional, and can &e used an)(here
2000 Prentice Hall, Inc. All rights reserved.

# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3 +4 +. +6 +/ +0 +9 30 3# 3+ 33 34

$$ %i&. 3.#+' (i&03)#+.c** $$ ; sco*in& exam*le -include <iostream> usin& std''cout; usin& std''endl; 9oid a( 9oid ); 9oid b( 9oid ); 9oid c( 9oid ); int x 1 #; int main() int x 1 .; $$ local 9ariable to main $$ (unction *rototy*e $$ (unction *rototy*e $$ (unction *rototy*e $$ &lobal

Outline

2;

1. Function prototypes 1.1 Initiali8e global 4ariable 1.2 Initiali8e local 4ariable 1.3 Initiali8e local 4ariable in bloc; 2. Call #unctions 3. Output results

x is di$$erent inside and outside 9ariable the &loc+.

cout << 3local x in outer sco*e o( main is 3 << x << endl; $$ start ne6 sco*e int x 1 /; cout << 3local x in inner sco*e o( main is 3 << x << endl; $$ end ne6 sco*e

"

cout << 3local x in outer sco*e o( main is 3 << x << endl; a(); $$ a has automatic local x b(); $$ b has static locallocal x x in outer sco*e o( main is . c(); $$ c uses &lobal x local x in inner sco*e o( main is / a(); $$ a reinitiali8es automatic local x sco*e o( main is . local x in outer b(); $$ static local x retains its *re9ious 9alue c(); $$ &lobal x also retains its 9alue 2000 Prentice Hall, Inc. All rights reserved.

3. 36 3/ 30 39 40 4# 4+ 43 44 4. 46 4/ 40 49 .0 .# .+ .3 .4 .. .6 ./ .0 .9 60 6# 6+ 63 64 6. 66 6/ 60

cout << 3local x in main is 3 << x << endl; return 0; " 9oid a( 9oid ) int x 1 +.; cout << << 22x; cout << << " 9oid b( 9oid ) static int x 1 .0; cout << << 22x; cout << << " 9oid c( 9oid )

Outline

2?

=ocal auto#atic varia&les are created and destro)ed each 3.1 "e#ine Functions ti#e a is called.
$$ initiali8ed each time a is called

endl << 3local x in a is 3 << x 3 a(ter enterin& a3 << endl; 3local x in a is 3 << x 3 be(ore exitin& a3 << endl;

local x in a is +. a(ter enterin& a local x in a is +6 be(ore exitin& a

$$ @tatic initiali8ation only destro)ed (hen the $unction $$ (irst time b is called. ends. endl << 3local static x is 3 << x 3 on enterin& b3 << endl; local static x is .0 on enterin& b 3local static x is 3 << x local static x is .# on exitin& b 3 on exitin& b3 << endl;

=ocal static varia&les are not

Elo&al varia&les are al(a)s accessi&le. Function c re$erences the glo&al x.


&lobal x is # on enterin& c &lobal x is #0 on exitin& c

cout << endl << 3&lobal x is 3 << x << 3 on enterin& c3 << endl; x !1 #0; cout << 3&lobal x is 3 << x << 3 on exitin& c3 << endl; 2000 Prentice Hall, Inc. All rights reserved. "

local x in outer sco*e o( main is . local x in inner sco*e o( main is / local x in outer sco*e o( main is . local x in a is +. a(ter enterin& a local x in a is +6 be(ore exitin& a local static x is .0 on enterin& b local static x is .# on exitin& b &lobal x is # on enterin& c &lobal x is #0 on exitin& c local x in a is +. a(ter enterin& a local x in a is +6 be(ore exitin& a local static x is .# on enterin& b local static x is .+ on exitin& b &lobal x is #0 on enterin& c &lobal x is #00 on exitin& c local x in main is .

Outline
Program Output

30

2000 Prentice Hall, Inc. All rights reserved.

3.12 (ecursion @ecursive $unctions

31

" Are $unctions that calls the#selves " Can onl) solve a &ase case " I$ not &ase case, the $unction &rea+s the pro&le# into a slightl) s#aller, slightl) si#pler, pro&le# that rese#&les the original pro&le# and
=aunches a ne( cop) o$ itsel$ to (or+ on the s#aller pro&le#, slo(l) converging to(ards the &ase case 6a+es a call to itsel$ inside the return state#ent

" %ventuall) the &ase case gets solved and then that value (or+s its (a) &ac+ up to solve the (hole pro&le#

2000 Prentice Hall, Inc. All rights reserved.

3.12 (ecursion %7a#ple2 $actorial


n" # n $ ( n % '" # ' $ (" (" # ( $ )"& )$(n%!)$&$

32

" @ecursive relationship / n" # n $ ( n %

)" 0

" 1ase case / " # *" # 0

2000 Prentice Hall, Inc. All rights reserved.

33 3.13 ,-ample 2sing (ecursion. 3he Fibonacci 1eries

Fi&onacci series2 0, 1, 1, 2, 3, 3, ;...


" %ach nu#&er su# o$ t(o previous ones " %7a#ple o$ a recursive $or#ula2
(ib(n) 1 (ib(n-#) 2 (ib(n-+)

C-- code $or (ibonacci $unction


lon& (ibonacci( lon& n ) i( ( n 11 0 NN n 11 # ) $$ base case return n; else return (ibonacci( n - # ) 2 (ibonacci( n O + ); "

2000 Prentice Hall, Inc. All rights reserved.

3' 3.13 ,-ample 2sing (ecursion. 3he Fibonacci 1eries

iagra# o$ Fi&onnaci $unction


f( 3 )

return

f( 2 )

f( 1 )

return

f( 1 )

f( 0 )

return 1

return 1

return 0

2000 Prentice Hall, Inc. All rights reserved.

# + 3 4 . 6 / 0 9 #0

$$ %i&. 3.#.' (i&03)#..c** $$ :ecursi9e (ibonacci (unction -include <iostream> usin& std''cout; usin& std''cin; usin& std''endl; unsi&ned lon& (ibonacci( unsi&ned lon& );

Outline

33

1. Function prototype 1.1 Initiali8e 4ariables 2. Input an integer 2.1 Call #unction (ibonacci 2.2 Output results. 3. "e#ine (ibonacci recursi4ely

## int main() #+ #3 #4 #. #6 #/ #0 #9 +0 " +# ++ $$ :ecursi9e de(inition o( (unction (ibonacci +3 unsi&ned lon& (ibonacci( unsi&ned lon& n ) +4 +. +6 +/ +0 i( ( n 11 0 NN n 11 # ) return n; else $$ recursi9e case $$ base case cout << 35nter an inte&er' 3; cin >> number; result 1 (ibonacci( number ); cout << 3%ibonacci(3 << number << 3) 1 3 << result << endl; return 0; unsi&ned lon& result4 number;

4nl) the &ase cases return values. All other cases call the (ibonacci $unction again.

return (ibonacci( n - # ) 2 (ibonacci( n - + ); +9 " 2000 Prentice Hall, Inc. All rights reserved.

5nter an inte&er' 0 %ibonacci(0) 1 0 5nter an inte&er' # %ibonacci(#) 1 # 5nter an inte&er' + %ibonacci(+) 1 # 5nter an inte&er' 3 %ibonacci(3) 1 + 5nter an inte&er' 4 %ibonacci(4) 1 3 5nter an inte&er' . %ibonacci(.) 1 . 5nter an inte&er' #0 %ibonacci(#0) 1 .. 5nter an inte&er' 6 %ibonacci(6) 1 0 5nter an inte&er' +0 %ibonacci(+0) 1 6/6. 5nter an inte&er' 30 %ibonacci(30) 1 03+040 5nter an inte&er' 3. %ibonacci(3.) 1 9++/46.

Outline
Program Output

35

2000 Prentice Hall, Inc. All rights reserved.

3.1 @epetition

(ecursion 4s. Iteration

38

" Iteration2 e7plicit loop " @ecursion2 repeated $unction calls

.er#ination
" Iteration2 loop condition $ails " @ecursion2 &ase case recogni<ed

1oth can have in$inite loops 1alance &et(een per$or#ance /iteration0 and good so$t(are engineering /recursion0

2000 Prentice Hall, Inc. All rights reserved.

3.1! Functions 5ith ,mpty Parameter Lists %#pt) para#eter lists


" %ither (riting 9oid or leaving a para#eter list e#pt) indicates that the $unction ta+es no argu#ents
9oid *rint(); or 9oid *rint( 9oid );

3;

" Function *rint ta+es no argu#ents and returns no value

2000 Prentice Hall, Inc. All rights reserved.

# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3 +4 +. +6 +/

$$ %i&. 3.#0' (i&03)#0.c** $$ %unctions that taMe no ar&uments -include <iostream> usin& std''cout; usin& std''endl; 9oid (unction#(); 9oid (unction+( 9oid ); int main() (unction#(); (unction+(); return 0; " 9oid (unction#() cout << 3(unction# taMes no ar&uments3 << endl; " 9oid (unction+( 9oid ) cout << 3(unction+ also taMes no ar&uments3 << endl; "

Outline

3?

Cotice the t(o (a)s o$ declaring no argu#ents.

1. Function prototypes 6ta;e no arguments7 2. Call the #unctions 3. Function de#initions

Program Output

(unction# taMes no ar&uments (unction+ also taMes no ar&uments

2000 Prentice Hall, Inc. All rights reserved.

3.1$ Inline Functions inline $unctions

'0

" @educe $unction-call overhead " As+s the co#piler to cop) code into progra# instead o$ using a $unction call " Co#piler can ignore inline " Dhould &e used (ith s#all, o$ten-used $unctions

%7a#ple2
inline double cube( const double s ) return s ! s ! s; "

2000 Prentice Hall, Inc. All rights reserved.

3.1% (e#erences and (e#erence Parameters Call &) value


" Cop) o$ data passed to $unction " Changes to cop) do not change original " Hsed to prevent un(anted side e$$ects

'1

Call &) re$erence


" Function can directl) access data " Changes a$$ect original

@e$erence para#eter alias $or argu#ent


P is used to signi$) a re$erence 9oid chan&e( int P9ariable ) 9ariable 21 3; "

" Adds 3 to the varia&le inputted


int y 1 Px.

" A change to y (ill no( a$$ect x as (ell


2000 Prentice Hall, Inc. All rights reserved.

# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3 +4 +. +6 +/ +0 +9 30 3#

$$ %i&. 3.+0' (i&03)+0.c** $$ ,om*arin& call-by-9alue and call-by-re(erence $$ 6ith re(erences. -include <iostream> usin& std''cout; usin& std''endl; int squareIyGalue( int ); 9oid squareIy:e(erence( int P ); int main() int x 1 +4 8 1 4; cout << << << << 3x 1 3 << x << 3 be(ore squareIyGalueQn3 3Galue returned by squareIyGalue' 3 squareIyGalue( x ) << endl 3x 1 3 << x << 3 a(ter squareIyGalueQn3 << endl;

Outline
1. Function prototypes 1.1 Initiali8e 4ariables 2. Print x 2.1 Call #unction and print x 2.2 Print 8 2.3 Call #unction and print 8

'2

Cotice the use o$ the P operator

cout << 38 1 3 << 8 << 3 be(ore squareIy:e(erence3 << endl; squareIy:e(erence( 8 ); cout << 38 1 3 << 8 << 3 a(ter squareIy:e(erence3 << endl; return 0; " int squareIyGalue( int a )

3. Function "e#inition o# squareIyGalue

" 2000 Prentice Hall, Inc. All rights reserved.

return a !1 a;

$$ callerRs ar&ument not modi(ied

32 33 9oid squareIy:e(erence( int Pc:e( ) 34 35 36 " x 1 + be(ore squareIyGalue Galue returned by squareIyGalue' 4 x 1 + a(ter squareIyGalue 8 1 4 be(ore squareIy:e(erence 8 1 #6 a(ter squareIy:e(erence c:e( !1 c:e(; $$ callerRs ar&ument modi(ied

Outline

'3

3.1 Function "e#inition o# squareIy:e(erence Program Output

2000 Prentice Hall, Inc. All rights reserved.

3.1' "e#ault /rguments

''

I$ $unction para#eter o#itted, gets de$ault value


" Can &e constants, glo&al varia&les, or $unction calls " I$ not enough para#eters speci$ied, right#ost go to their de$aults

Det de$aults in $unction protot)pe


int de(ault%unction( int x 1 #4 int y 1 +4 int 8 1 3 );

2000 Prentice Hall, Inc. All rights reserved.

# + 3 4 . 6 / 0 9

$$ %i&. 3.+3' (i&03)+3.c** $$ Dsin& de(ault ar&uments -include <iostream> usin& std''cout; usin& std''endl; int boxGolume( int len&th 1 #4 int 6idth 1 #4 int hei&ht 1 # );

Outline

'3

1. Function prototype 2. Print de#ault 4olume 2.1 Print 4olume 5ith one parameter 2.2 Print 5ith 2 parameters 2.3 Print 5ith all parameters. 3. Function de#inition

#0 int main() ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ " +3 +4 $$ ,alculate the 9olume o( a box +. int boxGolume( int len&th4 int 6idth4 int hei&ht ) +6 +/ return len&th ! 6idth ! hei&ht; +0 " 2000 Prentice Hall, Inc. All rights reserved. return 0; cout << 3Bhe de(ault box 9olume is' 3 << boxGolume() << 3QnQnBhe 9olume o( a box 6ith len&th #04Qn3 << 36idth # and hei&ht # is' 3 << boxGolume( #0 ) << 3QnQnBhe 9olume o( a box 6ith len&th #04Qn3 << 36idth . and hei&ht # is' 3 << boxGolume( #04 . ) << 3QnQnBhe 9olume o( a box 6ith len&th #04Qn3 << 36idth . and hei&ht + is' 3 << boxGolume( #04 .4 + ) << endl;

Bhe de(ault box 9olume is' # Bhe 9olume o( a box 6ith len&th #04 6idth # and hei&ht # is' #0 Bhe 9olume o( a box 6ith len&th #04 6idth . and hei&ht # is' .0 Bhe 9olume o( a box 6ith len&th #04 6idth . and hei&ht + is' #00

Outline
Program Output

'5

Cotice ho( the right#ost values are de$aulted.

2000 Prentice Hall, Inc. All rights reserved.

3.1+ 2nary 1cope (esolution Operator Hnar) scope resolution operator /''0
" Access glo&al varia&les i$ a local varia&le has sa#e na#e " not needed i$ na#es are di$$erent " instead o$ 9ariable use ''9ariable

'8

2000 Prentice Hall, Inc. All rights reserved.

# + 3 4 . 6 / 0 9 #0 ## #+ #3 #4 #. #6 #/ #0 #9 +0 +# ++ +3

$$ %i&. 3.+4' (i&03)+4.c** $$ Dsin& the unary sco*e resolution o*erator -include <iostream> usin& std''cout; usin& std''endl; -include <iomani*> usin& std''set*recision; const double JC 1 3.#4#.9+6.3.09/9; int main() const (loat JC 1 static)cast< (loat >( ''JC ); cout << set*recision( +0 ) << 3 Focal (loat 9alue o( JC 1 3 << JC << 3QnLlobal double 9alue o( JC 1 3 << ''JC << endl; return 0; "

Outline
1. "e#ine 4ariables 2. Print 4ariables

';

Cotice the use o$ ''

Focal (loat 9alue o( JC 1 3.#4#.9+/4#0#+./3+4+ Llobal double 9alue o( JC 1 3.#4#.9+6.3.09/9000/

Program Output

2000 Prentice Hall, Inc. All rights reserved.

3.20 Function O4erloading Function overloading

'?

" Having $unctions (ith sa#e na#e and di$$erent para#eters " Dhould per$or# si#ilar tas+s / i.e., a $unction to s!uare ints, and $unction to s!uare (loats0.
int square( int x) return x ! x;" (loat square((loat x) return x ! x; "

" Progra# chooses $unction &) signature


signature deter#ined &) $unction na#e and para#eter t)pes

" Can have the sa#e return t)pes

2000 Prentice Hall, Inc. All rights reserved.

# $$ %i&. 3.+.' (i&03)+..c** + $$ Dsin& o9erloaded (unctions 3 -include <iostream> 4 . usin& std''cout; 6 usin& std''endl; / 0 int square( int x ) 9 #0 double square( double y ) ## #+ int main() #3 #4 #. #6 #/ #0 #9 " return 0; cout << 3Bhe square o( inte&er / is 3 << square( / ) << 3QnBhe square o( double /.. is 3 << square( /.. ) << endl; return y ! y; " return x ! x; "

Outline
Functions have sa#e na#e &ut di$$erent para#eters 1. "e#ine o4erloaded #unction 2. Call #unction

30

Bhe square o( inte&er / is 49 Bhe square o( double /.. is .6.+.

Program Output

2000 Prentice Hall, Inc. All rights reserved.

3.21 Function 3emplates Function te#plates

31

" Co#pact (a) to #a+e overloaded $unctions " >e)(ord tem*late " >e)(ord class or ty*ename &e$ore ever) $or#al t)pe para#eter /&uilt in or user de$ined0
tem*late < class B > $$ or tem*late< ty*ename B > B square( B 9alue# ) return 9alue# ! 9alue#; "

B replaced &) t)pe para#eter in $unction call.


int x; int y 1 square(x); I$ int, all BIs &eco#e ints Can use (loat, double, lon&...
2000 Prentice Hall, Inc. All rights reserved.

You might also like