Sunteți pe pagina 1din 80

Cb[ecL CrlenLed rogrammlng

uslng C++
8 L 3
Lh
SemesLer
09LC364
laculLy rof Sankar uaslga
SLarL Cff
W 1exL 8ook
S 8 Llppman ! La[ole C++ rlmer" Addlson Wesley
3
rd
LdlLlon 2000
W 8eference 8ooks
1 Cohoon and uavldson C++ rogram ueslgn An
lnLroducLlon Lo rogrammlng and Cb[ecLCrlenLed
ueslgn" 1MP publlcaLlon 3
rd
LdlLlon 2004
2 8 Lafore Cb[ecL CrlenLed rogrammlng uslng C++"
CalgoLla ubllcaLlons 2004
W Pave a C++ compller / luL handy for Lrylng ouL
exerclses and asslgnmenLs
Some example C++ compllers / luLs are 1urbo C++ %luL
from 8orland) Dev C++ %luL from 8loodshed SofLware)
CeLLlng SLarLed
W rograms ofLen are wrlLLen ln response Lo some
problem or Lask Lo be solved
W Cne meLhod of solvlng a blg problem ls Lo break
lL down lnLo a number of smaller problems
Lhese smaller problems are easler Lo solve Lhls
sLraLegy ls known as divide ond conquer and
stepwise refinement
W 1o solve problems we Lyplcally use sequence of
sLeps called o/qorithm
A Sample C++ rogram
// My flrsL program
#lnclude losLream
vold maln%)

sLdcouL Pello Worldn"


// reLurn 0

Comment
reprocessor D|rect|ve
Iunct|on Name

8ody of the funct|on ma|n


Single line Comments in C++ begin with // (two consecutive forward slashes) while multiple line
comments start with /* (a slash and a star) and end with */ (a star and a slash)
- t is a good programming practice to write comments!! Comment pairs do not nest !!
%he preprocessor directive or the include declaration, #include <iostream>, makes available
input and output library functions such as 'cout' to the user program.
%he function main() is a special function that the system / OS executes first
- A complete program will have main() function
- %he key word 'void' implies that the function does not return any value
* Many a times non-return of any value is understood by default
- n this program the main() function does not have any parameters passed
Statement: s the smallest independent unit in a C++ program. An expression
terminated by a semicolon is referred to as a statement
- Eg., int no_of_students = 0;
no_of_students = students_of_section_A + students_of_sectionB;
cout << "the total number of students in 5
th
Sem. ECE at NM% is : " << no_of_students;
%he body of the function is contained between a pair of curly braces { and }
- return: Every function typically ends with a special statement : return <value>
tatement
reprocessor
reprocesslng ls Lhe flrsL sLep / pass of
compllaLlon or creaLlon of an execuLable from
C++ source flle%s) 1he preprocessor ls a LexL
processor LhaL uses speclal sLaLemenLs known
as dlrecLlves or conLrol sLaLemenLs LhaL cause
speclal compller acLlons such as flle lncluslon
%eg header flles) macro subsLlLuLlon
condlLlonal compllaLlon
1he %pre)processed flle%s) ls%are) Lhe lnpuL%s)
Lo Lhe nexL parL of compllaLlon
All preprocessor dlrecLlves begln wlLh Lhe #
symbol whlch musL occur ln Lhe lefLmosL
column of Lhe llne
Compller
ConverLs Lhe program lnLo an 'ob[ecL flle' wlLh
machlne execuLable lnsLrucLlons of Lhe
parLlcular compuLer sysLem / processor
Llnker
Llnks Lhe ob[ecL flles of Lhe llbrary funcLlons
and precomplled funcLlons of Lhe 'sofLware'
and produces Lhe acLual execuLable
W SofLware A collecLlon of relaLed programs
CreaLlon and 8unnlng of an LxecuLable %1 of 2)
ibrary Code
Source Code
Preprocessor
Compiler
Object Code
inker
Executable
Header Files
luL %lnLegraLed uevelopmenL LnvlronmenL)
lncludes all LhaL are necessary for creaLlon and runnlng of a
program / sofLware LdlLor Llbrary Compller uebugger and
few more faclllLles such as a pro[ecL flle eLc
Command Llne Compllers
'g++' ls a popular Cnu command llne compller
g++ hellocpp o hello
luLs also provlde Lhelr verslon of command llne compllers Lo
help fasL creaLlon of execuLables %Lg Lcc of 1urbo C++)
CperaLlng SysLem and 8unnlng of Lhe LxecuLable
1he CS loads Lhe 'execuLable' lnLo Lhe maln / 8AM memory
lnlLlallzes Lhe C allocaLes resources such as memory for
daLa sLorage schedules Lhe program for execuLlon eLc
CreaLlon and 8unnlng of an LxecuLable %2 of 2)
1he C++ rogram
W ln C++ an acLlon ls referred Lo as an expresslon
W An expresslon LermlnaLed by a semlcolon ls referred Lo as a
statement
Lg ch ch '0'
W Dec|arat|on sLaLemenL ldenLlfles a symbollc varlable or an ob[ecL
called an |dent|f|er wlLh an opLlonal lnlLlal value
Lg lnL book_counL 63
W ss|gnment
Lg book_counL books_on_shelf + books_on_order
W Comma Cperator
A seL of expresslons separaLed by commas ls a valld consLrucL
1hese expresslons are evaluaLed from lefL Lo rlgh
Lg lnL l [
l %[ 3 [ + 2)
1he C++ rogram
W Iunct|on
A funcLlon conslsLs of 4 parLs
W A reLurn Lype Lhe funcLlon name a parameLer llsL and Lhe funcLlon body
W 1he flrsL Lhree parLs are collecLlvely referred Lo as Lhe funcLlon proLoLype
W 1he parameLer llsL enclosed wlLhln parenLheses conLaln a commaseparaLed
llsL of zero or more parameLers
W 1he body of Lhe funcLlon ls enclosed wlLhln a palr of curly braces and conslsLs
of sequence of program sLaLemenLs
W reprocessor D|rect|ves pec|f|cat|on
reprocessor dlrecLlves are speclfled by placlng a pound slgn %#) ln Lhe
very flrsL column of a llne ln Lhe program
Lg #lnclude losLream
W lf Lhe flle name ls enclosed by angle backeLs %) Lhe flle ls presumed
Lo be a sLandard header flle 1he search Lo flnd lL wlll examlne a
predeflned seL of locaLlons
Lg #deflne MAx_8ullL8 312
W ueflnes a consLanL value
Iarlable
W A varlable ls an enLlLy LhaL has a value and ls known Lo Lhe program by a name and
lL ls addressable and lL's daLa value ls sLored aL some address
Lxamples of valld varlable names
l rank1 sLudenL_name MAx mln SLudenLMarks lloaL %C++ case senslLlve as such
lloaL ls dlfferenL from floaL)
Lxamples of lnvalld varlable names
a's %lllegal characLer aposLphe) sLudenL name %blank noL allowed) 1sLvalue %flrsL
characLer should be a leLLer) sLudenLname %comma noL allowed)
names should noL be Lhe same as a keyword Lhe followlng Lable provldes Lhe llsL of
keywords
asm
caLch
conLlnue
dynamlc_casL
exLern
goLo
muLable
proLecLed
shorL
sLrucL
Lrue
unlon
volaLlle
auLo
char
defaulL
else
false
lf
namespace
publlc
slgned
swlLch
Lry
unslgned
wchar_L
bool
class
deleLe
enum
floaL
lnllne
new
reglsLer
slzeof
LemplaLe
Lypedef
uslng
whlle
break
consL
do
expllclL
for
lnL
operaLor
relnLerpreL_casL
sLaLlc
Lhls
Lypld
vlrLual
case
consL_casL
double
exporL
frlend
long
prlvaLe
reLurn
sLaLlc_casL
Lhrow
Lypename
vold
8ullLln uaLa 1ypes
W C++ provldes bullLln supporL for prlmlLlve arlLhmeLlc daLa Lypes such as
lnLeger double preclslon and slngle preclslon floaLlng polnL boolean and
characLer
Lg lnL lval 1024
double dval 34139
floaL fval 314139
char achar 'a'
boolean resulL 18uL
W 1he arlLhmeLlc daLa Lypes provlde bullLln supporL for asslgnmenL and for Lhe
usual arlLhmeLlc operaLlons
Lg lnL lval2 lval1 + 4096 // addlLlon
lnL lval3 lval2 lval // subLracLlon
dval fval * lval // mulLlpllcaLlon
lval lval3 / 2 // dlvlslon
bool resulL lval2 lval3 // euallLy
resulL lval2 + lval ! lval3 // lnequallLy
resulL fval + lval2 dval // lessLhan
resulL lval lval2 // greaLerLhan
;uallflers and 1ypecasLlng
W ;uallflers
Slze 'shorL' and 'long' can be applled Lo daLa Lype
'lnL'
Lg shorL lnL long lnL
Slgn 'slgned' and 'unslgned' can be applled Lo
daLa Lypes 'char' and 'lnL'
Lg unslgned lnL l va|ue 0 to 2
16
2 8ytes
slgned char ch va|ue 128 to +127 1 8yte
1ypecasLlng
LxpllclL converslon of one daLa Lype Lo anoLher
%type) voriob/e_nome
Array uaLa 1ype %1 of 2)
W An array ls an ordered conLalner of elemenLs of a slngle Lype
Lg floaL my_array20
lnL flbon 0 1 1 2 3 3 8 13 21
W We access Lhe elemenLs of Lhe array by lndexlng 1he lndex of
flrsL elemenL of an array ls '0' %zero) As such Lhe nlne elemenLs
of flbon are lndexed aL poslLlons 0 Lo 8
W 1yplcally we sLep Lhrough Lhe elemenLs of an array uslng a for
loop
Lg lnL la10
for %lndex 0 lndex 10 ++lndex) lalndex lndex
noLe 1he sLaLemenL ++lndex ls shorLhand noLaLlon for
lncremenLlng an arlLhmeLlc ob[ecL by 1 lL ls equlvalenL Lo lndex
lndex + 1
Array uaLa 1ype %2 of 2)
Lg
consL lnL bufSlze 312 max_flles 20
lnL maxClassSlze 80
char lnpuL_bufferbufSlze // valld bufSlze ls consLanL
char flle1ablemax_flles 3 // valld ConsLanL expresslon
double marksmaxClassSlze // error non consLanL varlable
lnL la1 0 1 2 3
consL char ca1 'C' '+' '+ // slze 3
consL char ca2 C++" // slze 4
lnL LesL_scoresgeL_slze%) // error non consLanL expresslon
W MulLldlmenslonal Arrays
lnL la43 0 1 2 3 4 3 6 7 8 9 10 11 // lnlLlallzaLlon
lnL la43 0 1 2 3 4 3 6 7 8 9 10 11
consL lnL rowSlze 4 colSlze 3
lnL larowSlzecolSlze
CharacLer ConsLanL and Lscape Sequences
a 8eep
b 8ack Space
f lorm leed
n new Llne
L PorlzonLal 1ab
r Carrlage 8eLurn
8ack Slash
' Slngle ;uoLe
" uouble ;uoLe
v IerLlcal 1ab
? ;uesLlon Mark
0 null
0ooo Code ln CcLal %eg 0113 ls ASCll code of k)
xhh Code ln Pexa
A character constant is enclosed within single quotes, Eg., 'a'
Notations 'A' and "A' are different. %he second is a string constant!!
SLrlng uaLa 1ype
W A C++ sLrlng ls a characLer sequence LermlnaLed wlLh a null
characLer %'0')
Lg char my_sLrlng120
char my_sLrlng2 Pello"
W 1he LermlnaLlng null characLer %0) ls noL counLed ln lengLh of Lhe
sLrlng As such lengLh of Pello" ls 3
W 1he lndex of flrsL elemenL of a sLrlng ls '0' %zero)
0 08 08 0
Values of characters
my_string in memory
uynamlc Memory AllocaLlon and olnLers %1 of 2)
W under C++ ob[ecLs can be allocaLed elLher sLaLlcally or dynamlcally
Lg lnL lval 1024 // a sLaLlc varlable
W C++ supporLs a polnLer Lo hold memory address of values of ob[ecLs
Lg lnL *plnL // a polnLer Lo an ob[ecL Lo Lype lnL
plnL lval // asslgn plnL address of lval
W 1o access Lhe acLual ob[ecL plnL addresses we musL flrsL dereference plnL
uslng Lhe dereference operaLor %*)
Lg *plnL *plnL + 1 // ls same as lval lval + 1
W 1he Lwo prlmary dlfferences beLween sLaLlc and dynamlc memory allocaLlon
are
1 SLaLlc ob[ecLs are named varlables LhaL can be manlpulaLed dlrecLly whereas
dynamlc ob[ecLs are unnamed varlables LhaL can be manlpulaLed lndlrecLly uslng
polnLers
2 1he allocaLlon of memory for sLaLlc ob[ecLs ls handled auLomaLlcally by Lhe
compller whereas allocaLlon and deallocaLlon of memory for dynamlc ob[ecLs
wlll have Lo be managed by Lhe programmer
uynamlc Memory AllocaLlon and olnLers %2 of 2)
W AllocaLlon of dynamlc memory can be done uslng Lhe 'new'
expresslon whereas deallocaLlon of memory ls done uslng Lhe
'deleLe' expresslon
Lg lnL *plnL new lnL%1024) // allocaLes an unnamed ob[ecL
// of Lype lnL and lnlLlallzes lL Lo 1024
lnL *pla new lnL4 // allocaLes an array of four lnLs
deleLe plnL // deleLe a slngle ob[ecL
deleLe pla // deleLe an array of ob[ecLs
W 8elaLlonshlp of Array and olnLer 1ypes
Array ldenLlfler evaluaLes Lo Lhe address of Lhe flrsL elemenL
conLalned wlLhln lL
la ls same as la0 and *%la+1) ls same as la1
W Loglcal CperaLors
W 8lLwlse CperaLors
Operators and Expressions ( of )
Loglcal Anu
|| Loglcal C8
! Loglcal nC1
8lLwlse Anu
| 8lLwlse C8
8lLwlse xC8
ShlfL lefL
ShlfL rlghL
8lLwlse complemenL
W ArlLhmeLlc CperaLors + * |
Lg a +3 wlll add Lhe number 3 Lo Lhe value of a
a + bc bc wlll be evaluaLed flrsL and Lhen Lhe
resulL ls added Lo Lhe value of a
a 3 wlll shlfL Lhe blLs of a Lo Lhe lefL by 3
poslLlons
W lncremenL and uecremenL CperaLors
--votloble oome votloble oome
votloble oome-- votloble oome
Lg l ++[ Pere value of [ ls lncremenLed flrsL and Lhen
asslgned Lo l
l [ Pere value of [ ls asslgned Lo l flrsL and Lhen
decremenLed
Operators and Expressions
Conditional Operator
%est
Expression
Expression
Expression
Exit
False %rue
arge = i > j ? i : j;
Expression
Expression
%est Expression
W ArlLhmeLlc CperaLors
lnL x 16 y 3
W 8elaLlonal CperaLors
Operators and Expressions ( of )
+ AddlLlon x+ y 21
SubLracLlon x y 11
* MulLlpllcaLlon x * y 80
/ ulvlslon x / y 3 %declmal parL dlscarded)
Modulo dlvlslon x y 1 %remlnder of dlvlslon)
Less Lhan lf %l [)
CreaLer Lhan lf %l [)
Less Lhan or equal lf %l [)
CreaLer Lhan or equal lf %l [)
Lqual Lo lf %l [)
! noL equal Lo lf %l ! [)
slzeof CperaLor
W 1he slzeof operaLor reLurns Lhe slze ln byLes of an
ob[ecL or daLa Lype
char A slngle byLe LhaL holds a one characLer slzeof%char) 1 byLe
lnL An lnLeger slzeof%lnL) 2 byLes
floaL A slngle preclslon floaLlng polnL number slzeof%floaL) 4 byLes
double A double preclslon floaLlng polnL number slzeof%double) 8 byLes
shorL A shorL lnLeger slzeof%shorL) 2 byLes
Slze of a polnLer slzeof%shorL *) 4 byLes
A shorL lnLeger slzeof%shorL ) 2 byLes
la10 An array of 10 lnLegers slzeof%la) 20 byLes
LlLeral ConsLanLs
ConsL ;uallfler
W consL ;uallfler
Many a Llmes we wlll be needlng Lo use consLanL values such
as value of 'pl' 'buffer slze' eLc aL several places ln our code /
programs lL ls cumbersome or error prone Lo use Lhe acLual
values such as 314 %for pl) or 312 %for 8uffer Slze) every
Llme
'consL' quallfler allows us Lo declare a named consLanLs ln
such scenarlos
Lg consL double pl 314
consL lnL bufSlze 312
Cnce a consLanL ls deflned we can noL change Lhe value
assoclaLed wlLh lL
bufSlze 1024 // ls noL allowed wlLhln Lhe code
// lL ls a compllaLlon error
lnL *lpLr bufSlze // ls noL allowed lL ls a complle Llme
//error
ConsL ;uallfler
W consL ;uallfler
consL lnL bufSlze 312
lnL maxClassSlze 80
consL lnL *cpLr 0
cpLr bfSlze //Ck
cpLr maxClassSlze //Ck
*cpLr 100 // complle Llme error
W 8eference 1ypes
A reference ls also referred Lo as an 'allas' serves as
an alLernaLe name for an ob[ecL
lnL lval 1024
lnL refIal lval
8oolean and LnumeraLlon 1ypes
W 1he boolean 1ype
A bool ob[ecL can be asslgned Lhe llLeral values Lrue or false
bool found Lrue
W LnumeraLlon 1ypes
CfLen when we program we need Lo deflne a seL of
alLernaLlve aLLrlbuLes Lo assoclaLe wlLh an ob[ecL
Lg consL lnL lnpuL 1
consL lnL ouLpuL 2
consL lnL append 3
bool open_flle%sLrlng flle_name lnL open_mode)
enum open_modeslnpuL 1 ouLpuL append
We can also say open_modes om lnpuL
Lxample 1_1
/* Example program: Usage of - few basic data types and operations, functions */
#include <iostream> // file name enclosed in angle brackets is presumed to be a standard header or project file
using namespace std;
#define MAXUSN 0 // pre-processor directive so that the word MAXUSN can be used instead of the number 0
int marks; // global variable
void get_student_usn(char *); void get_student_marks(); // prototypes of a functions
float get_student_marks(){
float student_marks;
cin >> student_marks;
return(student_marks);
}
main(){
int marks;
char name[0], *usn;
bool end_of_data_entry = true;
cout << "Enter the student information in the order: Name usn marks of sub and sub" << endl;
usn = new char(MAXUSN);
while(end_of_data_entry){
cin >> name;
if (name[0] == 'z'){ end_of_data_entry = false; continue;}
get_student_usn(usn);
marks = (int) get_student_marks();
get_student_marks();
cout << name << " " << usn << " " << marks << " " << marks << endl;}
cout << "End of data entry" << endl;
getchar(); getchar();
}
void get_student_usn(char *ch){
cin >> ch;
}
void get_student_marks(){
cin >> marks;
}
An Cb[ecLbased ueslgn
W C|ass
Lxample 1_2 %1 of 3)
// ntArray Class
#include <iostream>
using namespace std;
class ntArray{
public:
explicit ntArray(int sz = DefaultArraySize);
ntArray(int *array, int array_size);
~ntArray(){delete [] ia;}
int size();
int max();
int min();
void swap(ntArray&, int, int);
int& operator[] (int index){return ia[index];}
// ntArray& operator = (const ntArray&); {return ia;}
private:
void init(int sz, int *array);
static const int DefaultArraySize = ;
int *ia;
int _size;
};
Lxample 1_2 %2 of 3)
ntArray::ntArray(int sz){init(sz, 0);}
ntArray::ntArray(int *array, int sz) {init(sz, array);}
void ntArray::init(int sz, int *array)
{
_size = sz;
ia = new int[_size];
for (int i = 0;i < _size;i++)
if (!array) ia[i] = 0;
else ia[i] = array[i];
}
int ntArray::size()
{
return _size;
}
void ntArray::swap(ntArray &ia, int i, int j)
{
int tmp = ia[i];
ia[i] = ia[j];
ia[j] = tmp;
}
int ntArray::max()
{
int tmp = ia[0];
for (int i = ;i < _size;i++)
if (ia[i] > tmp) tmp = ia[i];
return tmp;
}
int ntArray::min()
{
int tmp = ia[0];
for (int i = ;i < _size;i++)
if (ia[i] < tmp) tmp = ia[i];
return tmp;
}
Lxample 1_2 %3 of 3)
main()
{
int ia[0] = {0, , , 33, 4, 55, 6, , 88, 9}, *iap;
ntArray ia(ia, 0), ia;
for (int i = 0;i < 0; i++) cout << " ia["<<i<<"] = "<<ia[i];
cout <<endl << endl;
cout <<"ia size = "<< ia.size()<< endl;
cout <<"5th element in ia of ia = "<< ia[5] << endl << endl;
cout <<"ia size = " << ia.size() <<endl << endl;
cout << "ia[5] before assigning ia to ia = " << ia[5]<< endl;
cout <<"ia[0] = " << ia[0] << " ia[] = " << ia[] <<endl << endl;
ia = ia;
cout <<"ia[5] after assigning ia to ia = " <<ia[5] << endl;
cout <<"ia size afeter assigning ia to ia = " << ia.size() <<endl;
cout <<"ia[0] = " << ia[0] << " ia[] = " << ia[] <<endl << endl;
ia.swap(ia, 3, 5);
cout <<"ia[3] after swap = " <<ia[3] << endl;
cout <<"max in ia is = " << ia.max() << endl;
cout <<"min in ia is = " << ia.min() << endl;
getchar();
}
SLrlng Class
An Cb[ecLorlenLed ueslgn
W nher|tance
8ase c|ass Der|ved c|ass
Mu|t|p|e |nher|tance and v|rtua| |nher|tance
Lxample 1_3 %1 of 3)
/* Example program: inheretance */
#include <iostream>
#include <cassert>
using namespace std;
class ntArray{
public:
explicit ntArray(int sz = DefaultArraySize);
ntArray(int *array, int array_size);
~ntArray(){delete [] ia;}
int size();
int max();
int min();
void swap(ntArray&, int, int);
int& operator[] (int index){return ia[index];}
protected:
void init(int sz, int *array);
static const int DefaultArraySize = ;
int *ia;
int _size;
};
ntArray::ntArray(int sz){init(sz, 0);}
ntArray::ntArray(int *array, int sz) {init(sz, array);}
void ntArray::init(int sz, int *array)
{
_size = sz;
ia = new int[_size];
for (int i = 0;i < _size;i++)
if (!array) ia[i] = 0;
else ia[i] = array[i];
}
Lxample 1_3 %2 of 3)
int ntArray::size()
{
return _size;
}
void ntArray::swap(ntArray &ia, int i, int j)
{
int tmp = ia[i];
ia[i] = ia[j];
ia[j] = tmp;
}
int ntArray::max()
{
int tmp = ia[0];
for (int i = ;i < _size;i++)
if (ia[i] > tmp) tmp = ia[i];
return tmp;
}
int ntArray::min()
{
int tmp = ia[0];
for (int i = ;i < _size;i++)
if (ia[i] < tmp) tmp = ia[i];
return tmp;
}
Lxample 1_3 %3 of 3)
class ntArrayRC : public ntArray{
public:
ntArrayRC(int sz = DefaultArraySize);
ntArrayRC(int *array, int array_size);
int& operator[](int);
private:
void check_range(int);
};
ntArrayRC::ntArrayRC(int *array, int sz) {init(sz, array);}
inline int&
ntArrayRC::operator [] (int index)
{
check_range(index);
return ia[index];
}
inline void
ntArrayRC::check_range(int index)
{
assert(index >= 0 && index < _size);
}
void swap(ntArray &ia, int i, int j){
int tmp = ia[i];
ia[i] = ia[j];
ia[j] = tmp;
}
main(){
int ia[0] = {0, , , 33, 4, 55, 6, , 88, 9}, *iap;
ntArray ia(ia, 0); ntArrayRC ia(ia, 0);
cout <<"ia[3] = " << ia[3] << " ia[4] = " << ia[4] <<endl << endl;
cout << "swap() with ntArray ian";
swap(ia, , ia.size());
cout << "swap() with ntArray ian"; swap(ia, , ia.size());
}
An LxcepLlonbased ueslgn
W lL ls someLlmes necessary Lo perform repeaLed
acLlons or sklp some sLaLemenLs lor Lhls C++
provldes a seL of declslon maklng and loop
sLaLemenLs / consLrucLs
ueclslon maklng sLaLemenLs
W lf sLaLemenL
W lf else sLaLemenL
W swlLch sLaLemenL
Loop consLrucLs
W forloop
W whlleloop
W dowhlle loop
Control Flow
Control Flow: if Statement
%est
Expression
Body of if
Exit
False
%rue
if (expression)
{
statement;
....
statement;
}
/* Example */
races are used when
there are more than one
statement to be
executed depending on
the condition
Control Flow: if-else Statement
if (expression)
{
statement;
else
statement;
}
/* Example */
%est
Expression
Body of
if
Exit
False
%rue
Body of
Else
Control Flow: Nested
%est
%est
Body of second
if statement
Optional:
Body of last else
statement
Exit
False
False
%rue
%rue
%est
%est Body
False
%rue
Body
%rue
%est 3 Body 3
False
%rue
False
Exit
if if- -eIse eIse Ise Ise- -if if
ptionaI: ody for Iast /
defauIt eIse statement.
Can be used for error
handIing
Control Flow: Nested if-else
/* Example of nested if-else */
ote: eIse aIways associates itseIf with the cIosest if that does not aIready have an eIse
Control Flow: Switch Statement
Switch variable
equals
st
case
constant
Switch variable
equals
nd
case
constant
Body of
st
case
Body of
nd
case
Body of
Default
Exit
%rue
%rue
False
False
A switch statement allows the
user to choose a statement or
group of statements among
several alternatives
switch(n)
{
case :
statement ;
statement;
break;
case :
statement;
statement;
break;
..
..
default:
statement;
statement;
break;
}
switch statement is easier to program
and read than the nested if-eIse
statement
Integer or char
variabIe
ote: cases / defauIt
cIause can occur in
any order
ote: Without
break
execution faIIs
through
reak after the Iast case is
optionaI
Control Flow: For oop
nitialization of
Expression
%est
Expression
Body of loop
Update
Expression
Exit
False
%rue
for loop is useful when a statement has to
be executed a number of times
for (expr; expr; expe3)
statement;
Any of the exprs
can be omitted
If the test expr2 is omitted, it is taken as
permanentIy true!!
for (;;;) { .. } is an infinite Ioop!! A
break or return is needed to beak this
Ioop
Control Flow: While oop
%est
Expression
Exit
Body of oop
False
%rue
while (expression)
statement;
whiIe loop is useful when the number of
times a loop has to be executed is not
known in advance
for (expr; expr; expr3)
statement;
is equivaIent to
expr;
while (expr){
statement
expr3;
}
Control Flow: Do-While oop
%est
Expression
Exit
Body of oop
False
%rue
do whiIe tests the terminating condition at
the bottom, as such 'body of the loop' gets
executed atleast once
do
statement
while (expression);
do whiIe is not used as frequently as the
'for 'or 'whiIe do' loops in programming !!
Control Flow: continue and goto
Statements
Continue
within loop
Continue;
Remaining part
of the loop
Start of oop
%rue
False
Normal
oop
Return
continue is used to bypass the
reminder of the current pass through
the loop
goto is used to alter normal
sequence of program execution
Note: continue and goto are seldom used in
programs!!
Note: continue inside a for loop causes
passing of control to the next increment
W A number of lnsLrucLlons grouped lnLo a slngle loglcal unlL ls
referred Lo as a funcLlon
W luncLlons make Lhe whole program sLrucLured manageable
malnLalnable and readable
W luncLlons help reuse of parLs of code developed by programmers
across Lhe organlzaLlon for LhaL maLLer across Lhe globe!!
Code reuse ls an key aspecL of SofLware Lnglneerlng
W luncLlons LhaL are well lmplemenLed and LesLed can be used as a
llbrary wlLhln Lhe organlzaLlon
W Llbrary funcLlons perform common Lasks LhaL a program or
sofLware ofLen requlres
W Llbrary funcLlons need noL be complled each Llme and can be
lncluded or llnked and loaded on need basls
W 1he funcLlon maln%) ln Lhe program ls execuLed flrsL
W 1he oLher funcLlons are execuLed when Lhe maln%) funcLlon calls
Lhem dlrecLly or lndlrecLly %maln%) calllng a funcLlon whlch ln Lurn
calls oLher funcLlons and so on)
Functions
Structure and Execution of Functions
return_type function_name(param, param, .)
{
declarations of local variables;
statement;
statement;
....
....
return(function type / success / error code);
}
pre-processor directives
global declarations
main()
{
local variables of function main;
Statements associated with function main;
variabIe = f1(param1, param2, .);
Statements associated with function main;
}
return_type f(param, param, ..)
{
local variabled of function
statements associated with function ;
return(function_type);
}
Push PC (of main())
Push parameters
oad PC (address of first
instruction of f())
Pop parameters
Execute body of f()
Pop PC (of main())
%ypical steps that the
system / OS executes
We can have a function with no
parameters passed also
Default return_type is 'int'
Keyword 'void' is used when the
function does not return any
value
Scope of Variables
pre-processor directives
declaration of global variables
nt i;
main()
{
local variables of function main;
int j, k, p;
Statements associated with function main;
for (j = 0; j < i; j++){
int k ;
..
..
}
k = j * i;
....
p = f1(j, k);
More statements associated with function main;
}
int f(int x, int j)
{
local variabled of function
int k;
k = i * j * x;
return(k);
}
LocaI to main( )
LocaI to for Ioop
'i' is gIobaI to the program
LocaI j and k of main( )
LocaI to f1( )
nd of scope of LocaIs of for Ioop
nd of scope of LocaIs of main( )
nd of scope of IocaIs of f1( )
GIobaI 'i' and copy of 'j' passed
GIobaI 'i' and 'j' which is IocaI to main( )
W A C++ program conslsLs of a seL of exLernal ob[ecLs whlch are elLher varlables or
funcLlons
W LxLernal" ls used ln conLrasL Lo lnLernal" whlch descrlbes Lhe argumenLs and
varlables deflned lnslde funcLlons
W LxLernal varlables are deflned ouLslde of any funcLlon and are Lhus poLenLlally
avallable Lo many funcLlons
W luncLlons Lhemselves are always exLernal because C++ does noL allow funcLlons
Lo be deflned lnslde oLher funcLlons
W 8y defaulL exLernal varlables and funcLlons have Lhe properLy LhaL all references Lo
Lhem by Lhe same name even from funcLlons complled separaLely are references
Lo Lhe same Lhlng
External Variables
pre-processor directives
int i;
extern f();
main()
{ int j, k, p;
local variables of function main;
Statements associated with function main;
p = f1(j, k);
k = f();
}
int f(int x, int j){
...
}
extern int i;
int f(int x, int y){
x= i * y;
...
}
'i' is externaI and
decIared in the
other fiIe
Arguments Pass by Value and Pass by
Reference
pre-processor directives
global declarations
main()
{
local variables of function main;
Statements associated with function main;
variabIe = f1(param1, param2);
Statements associated with function main;
}
int f(int param, int param)
{
local variabled of function
statements associated with function ;
....
if (..) param1 = param1 * param2;
....
return(param1);
}
param
param
Data store
of main
param
param
Copy
param1
eneral mechanism of passing parameters to
functions in C is by value
Passing by reference is possible in
by passing of the address of the
variable(s) to the function. n which
case direct manipulation of the
variable is possible.
However this approach is risky!!
strings and arrays however are
passed by reference!!
W A funcLlon musL be declared Lo Lhe program before lL ls called
%oLherwlse a complleLlme error resulLs)
W Iunct|on rototype A funcLlon proLoLype conslsLs of 1 funcLlon
reLurn Lype 2 Lhe name of Lhe funcLlon and 3 Lhe parameLer llsL
Lg lnL abs%lnL)
W n||ne Iunct|on lf Lhe funcLlon has been declared in/ine Lhe body of
Lhe funcLlon ls expanded aL Lhe polnL of lLs call durlng compllaLlon
lf lLs noL declared lnllne Lhe funcLlon ls lnvoked aL runLlme
lnllne funcLlons have mlnlmum runLlme overheads
Functions
nline int abs(int iobj)
{
// return the absolute valie of iobj
return(iobj < 0 ? iobj : iobj);
}
W Iunct|on Cver|oad|ng ln C++ lL ls posslble Lo have Lwo funcLlons wlLh Lhe same name and dlfferenL
parameLer llsLs
1he parameLer llsL ls referred Lo as Lhe siqnoture of Lhe funcLlon as lL dlsLlngulshes one lnsLance of
Lhe funcLlon from anoLher
Lg lnLArraylnLArray%lnL sz) // elemenLs of array lnlLlallzed by defaulL Lo 0
lnLArraylnLArray%lnL *array lnL sz)
W C++ ls a stronq typed language 1he argumenLs of every funcLlon call are typechecked durlng
compllaLlon
lmpllclL converslons such as double Lo lnL however are applled wherever posslble
W Defau|t rguments A defaulL argumenL ls a value
alLhough noL unlversally appllcable ls [udged Lo be an
approprlaLe argumenL value for a parameLer ln a
ma[orlLy of cases
Lg char *screenlnlL%lnL helghL 24 lnL wldLh 80 char
background ' ')
Functions
W eturn Va|ues Vs g|oba| Cb[ects
urawbacks of relylng on global ob[ecLs Lo communlcaLe beLween funcLlons are
1 A funcLlon LhaL uses Lhe global ob[ecL depends on Lhe exlsLence and
Lype of Lhose ob[ecLs
2 lnLroducLlon of local changes Lo funcLlons requlres knowledge of global
ob[ecLs
3 lf global ob[ecLs geL lncorrecL values Lhe enLlre program wlll have Lo be
searched Lo deLermlne where Lhe error occurs
4 8ecurslon ls more dlfflculL Lo geL rlghL when global ob[ecLs are used by
Lhe funcLlon
3 ln Lhe presence of Lhreads speclal codlng ls requlred Lo synchronlze
readlng and wrlLlng of global ob[ecL among Lhe varlous Lhreads
Functions
W rgument ass|ng ass by va|ue
ass by vale ls noL sulLable for Lhe slLuaLlons
1 When a large class ob[ecL musL be passed as an
argumenL Lhe Llme and space cosLs Lo allocaLe and
copy onLo sLack ls Loo hlgh
2 When Lhe values of Lhe argumenLs musL be
modlfled
Lg vold swap %l [) // swapping of two values
W eference arameters
1hls mechanlsm of parameLer passlng ls approprlaLe when
Lhe funcLlon ls requlred Lo reLurn addlLlonal resulLs Lo Lhe
calllng funcLlon
Lg a look_up%) funcLlon reLurnlng a locaLlon of a parLlcular
value as well as Lhe number of Llmes lLs occurrence
wlLhln a daLa seL
Functions
W rray arameters
are passed as a polnLer Lo Lhe flrsL LhaL ls zeroLh elemenL
Lg vold puLIal%lnL10) ls LreaLed as vold puLIal%lnL *)
1here are Lwo lmpllcaLlons due Lo Lhe passlng of arrays by reference
1 Changes Lo array parameLers wlLhln Lhe called funcLlon are made Lo Lhe
array argumenL lLself and noL Lo a local copy
4 rogrammers wlll need Lo keep a copy of Lhe orlglnal array lf Lhe
requlremenL ls Lo noL Lo change Lhe orlglnal argumenL Lhls ls a
small overhead!!
2 1he slze of Lhe array ls noL parL of lLs parameLer Lype As such Lhe
funcLlon belng passed an array nor Lhe compller would know Lhe slze of
Lhe array
4 Cne common approach Lherefore ls Lo provlde an addlLlonal
argumenL LhaL conLalns Lhe array's slze
W |||pse
SomeLlmes lL may noL be posslble Lo llsL Lhe Lype and number of all
argumenLs LhaL mlghL be passed Lo a funcLlon ln Lhese cases elllpses
%) can be speclfled ln Lhe funcLlon parameLer llsL Llllpses suspend
Lypechecklng by Lhe compller
Lg vold myluncLlon%)
%he standard C library O/P function is an example in which an ellipse is necessary !!
And, printf()'s first parameter is always a C-style character string, as such
Eg, int printf(const char* .)
Functions
W eturn|ng a va|e
8eLurn sLaLemenL ls used Lo reLurn a value from a funcLlon
Lg reLurn expresslon
8y defaulL Lhe value reLurned by a funcLlon ls passed by
value
lf Lhe reLurn value ls a large class ob[ecL uslng a reference
%or polnLer) reLurn Lype ls more efflclenL
4 Powever reLurnlng by reference has Lwo poLenLlal
plLfalls
1 1he llfeLlme of Lhe local ob[ecL LermlnaLes wlLh Lhe
LermlnaLlon of Lhe funcLlon and Lhe reference ls lefL
allaslng undeflned memory
2 Any modlflcaLlon of Lhe value reLurned changes Lhe
acLual ob[ecL belng reLurned
W 1o prevenL Lhe unlnLended modlflcaLlon of a
reference reLurn value Lhe reLurn value should be
declared as const
W A sofLware wlll have a good number of funcLlons whlch are grouped lnLo
few 'source' flles
Lg all Lhe ul funcLlons ln one flle funcLlons relaLed
Lo u8 operaLlons ln one anoLher flle and so on
W A sofLware wlll also have many common declaraLlons such as buffers %Lg
8ead buffer wrlLe buffer) consLanLs %eg MAxIAL 8ulSlZL) eLc whlch all
Lhe funcLlons across 'source' flles use / access / updaLe
W A 'header flle' ls one whlch has Lhe declaraLlons common Lo many funcLlons
and 'proLoLypes' of funcLlons used across Lhe 'source' flles of a sofLware
W 1he header flle%s) are lncluded ln Lhe 'source' flle wlLh a #lnclude dlrecLlve
Lg #lnclude my_headerh"
noLe Lhe dlfference beLween lncludlng a C++ llbrary flle Is lncludlng a
header flle
#lnclude losLream vs #lnclude /my_llb/my_headerh"
Header Files
W An algorlLhm ls sald Lo be recurslve lf lL lnvokes lLself and has a LermlnaLlng
condlLlon
lf an algorlLhm lnvokes lLself and Lhe lnvoklng sLaLemenL ls presenL ln Lhe body
of Lhe algorlLhm Lhen Lhe algorlLhm ls sald Lo be 'dlrecL recurslve'
An algorlLhm ls sald Lo be 'lndlrecL recurslve' lf lL calls anoLher algorlLhm whlch
ln Lurn calls A
We wlll look aL a funcLlon LhaL would flnd Lhe facLorlal of a glven number as
example for recurslon here
8ecurslon
#include <iostream>
main(){
cout <<"Enter the number:;
cin >> &i;
cout << "Factorial of the given
No. is: << fact(i));
}
int fact(int n)
{
if (n <= ) return ;
else return(n*fact(n-));
}
Eg.,
Fact() = * fact(6)
= * 6 * fact(5)
= * 6 * 5 * fact(4)
= * 6 * 5 * 4 * fact(3)
= * 6 * 5 * 4 * 3 * fact()
= * 6 * 5 * 4 * 3 * * fact()
= * 6 * 5 * 4 * 3 * *
= 5040
Functions
W rray arameters
are passed as a polnLer Lo Lhe flrsL LhaL ls zeroLh elemenL
Lg vold puLIal%lnL10) ls LreaLed as vold puLIal%lnL *)
1here are Lwo lmpllcaLlons due Lo Lhe passlng of arrays by reference
1 Changes Lo array parameLers wlLhln Lhe called funcLlon are made Lo Lhe
array argumenL lLself and noL Lo a local copy
4 rogrammers wlll need Lo keep a copy of Lhe orlglnal array lf Lhe
requlremenL ls Lo noL Lo change Lhe orlglnal argumenL Lhls ls a
small overhead!!
2 1he slze of Lhe array ls noL parL of lLs parameLer Lype As such Lhe
funcLlon belng passed an array nor Lhe compller would know Lhe slze of
Lhe array
4 Cne common approach Lherefore ls Lo provlde an addlLlonal
argumenL LhaL conLalns Lhe array's slze
W |||pse
SomeLlmes lL may noL be posslble Lo llsL Lhe Lype and number of all
argumenLs LhaL mlghL be passed Lo a funcLlon ln Lhese cases elllpses
%) can be speclfled ln Lhe funcLlon parameLer llsL Llllpses suspend
Lypechecklng by Lhe compller
Lg vold myluncLlon%)
%he standard C library O/P function is an example in which an ellipse is necessary !!
And, printf()'s first parameter is always a C-style character string, as such
Eg, int printf(const char* .)
Functions
W eturn|ng a va|e
8eLurn sLaLemenL ls used Lo reLurn a value from a funcLlon
Lg reLurn expresslon
8y defaulL Lhe value reLurned by a funcLlon ls passed by
value
lf Lhe reLurn value ls a large class ob[ecL uslng a reference
%or polnLer) reLurn Lype ls more efflclenL
4 Powever reLurnlng by reference has Lwo poLenLlal
plLfalls
1 1he llfeLlme of Lhe local ob[ecL LermlnaLes wlLh Lhe
LermlnaLlon of Lhe funcLlon and Lhe reference ls lefL
allaslng undeflned memory
2 Any modlflcaLlon of Lhe value reLurned changes Lhe
acLual ob[ecL belng reLurned
W 1o prevenL Lhe unlnLended modlflcaLlon of a
reference reLurn value Lhe reLurn value should be
declared as const
Functions
W n||ne Iunct|ons
Conslder Lhe followlng funcLlon
lnL mln%lnL v1 lnL v2)
reLurn%v1 v2 ? v1v2)

1he beneflLs of deflnlng such a small funcLlon are


1 lL ls easler Lo read a call Lo mln%) Lhan readlng every lnsLance of Lhe condlLlonal
operaLor ln Lhe code parLlcularly when v1 and v2 are complex expresslons
2 lL ls easler Lo change one locallzed lmplemenLaLlon
3 SemanLlcs are conslsLenL and each LesL ls guaranLeed Lo work ln Lhe same manner
4 1he funcLlon can be reused
8uL a small funcLlon lmplemenLed as above has overheads and lnllne funcLlons provlde
a soluLlon
Lg lnllne lnL mln%lnL v1 lnL v2) return(v < v ? v:v);}
Powever Lhe lnllne speclflcaLlon ls only a recommendaLlon Lo Lhe compller whlch lL
may lgnore lf Lhe expanslon aL Lhe polnL of call ls lmpracLlcal such as a 1200 llne
funcLlon!!
ln general lnllne mechanlsm ls meanL Lo opLlmlze small sLralghLllne frequenLly called
funcLlons
An lnllne funcLlon deflned musL be vlslble Lo Lhe compller le lL should be avallable ln
every source flle A convenlenL mechanlsm Lherefore ls Lo declare lL ln Lhe pro[ecL
header flle LhaL every source flle lncludes
Expetion Handling
W LxcepLlons are runLlme anomalles such as
ulvlslon by Zero
Access of an array ouLslde of lLs bounds
Memory noL avallable
W C++ language provldes bullLln language feaLures or
mechanlsm Lo communlcaLe excepLlons beLween Lwo
unrelaLed / separaLe porLlons of programs
W 1hrow|ng an except|on
When an excepLlon ls encounLered ln a C++ program
Lhe porLlon of Lhe program LhaL deLecLs Lhe excepLlon
communlcaLes Lhe same by throwinq an excepLlon
1o ooJetstooJ tbe mecboolsm let os cooslJet tbe
exomple closs l5otck
%hrowing an Exception Example:- class iStack
incIude <vector>
CIass iStack{
pubIic:
iStack(int capacity)
: _stack(capacity), _top(0) { }
booI pop(int &top_vaIue);
booI push(int vaIue);
booI fuII();
booI empty();
void dispIay();
int size();
private:
int _top;
vector<int> _stack;
}
When the iStack object is created, the constructor creates a vector of ints of specified
size. For, Eg., 0 int values with the declaration, iStack myStack(0);
%hings that can possibly go wrong when myStack is manipulated are : . Stack is empty
when a pop() operation is done, . Stack is full when push() operation is done
As such we could define two exceptions to handle the above anomalies,
class popOnEmpty { ...};
class pushOnFull { ...};
We then change the definition
of the member functions pop()
and push() to throw the newly
defined exceptions.
An exception is thrown using
throw exception
Eg., throw popOnEmpty();
throw pushOnFull();
Note: the throw expression
looks similar to return
statement of a function
We could place these two classes in a header file, say
stackExcp.h
With exception
incorporated pop() and
push() can have return
type void
%hrowing an Exception Example:- class iStack
incIude "stackxcp.h"
void iStack::pop(int &top_vaI)
{
if (empty()) throw popnmpty();
top_vaIue = _stack[--_top];
}
void iStack::push(int vaIue)
{
if (fuII()) throw pushnFuII();
_stack[_top++] = vaIue;
}
mplementation of pop() and push() member functions of iStack
along with the handle for exceptions
%hrowing an Exception Example:- class iStack
incIude <iostream>
incIude "iStack.h"
int main()
try{
iStack stack(32);
stack.dispIay();
for (int ix = 1; ix < 51; ++ix){
if (ix %3 == 0)
stack.push(ix);
if (ix %4 == 0)
stack.dispIay();
if (ix %10 == 0){
int dummy;
stack.pop(dummy);
stack.duspIay():
return 0;
}
catch (pushnFuII){
cerr << "Stack is fuII\n";
return errorCode88;
}
catch (popnmpty){
cerr << "Stack is empty\n";
return errorCode89;
}
The try bIock:
W A try bIock encIoses statements that can
throw exceptions.
W FoIIowing the throw bIock are the
handIes caIIed catch cIauses
(The code on the LHS pushes on the stack
vaIues that are muItipIes of 3, dispIays
vaIues that are muItipIes of 4 and pops
vaIues that are muItipIes of 10)
1. If no exception occurs, the code within
the try bIock is executed and the
handIers associated with the try bIock
are ignored. The function main() returns 0
2. If the push() member function throws an
exception, the second and third if
statements of the for Ioop are ignored,
the for Ioop and try bIock are exited, and,
the handIer of exception of the type
pushnFuII is executed
3. SimiIarIy, if the pop() member function
throws an exception, caII to dispIay() is
ignored , for Ioop and try bIocks are
exited and popnmpty is executed
f no catch clause handles the exception, C++ library's terminate() function will get executed
Note: A try block introduces a local scope!!
Catching an Exception
W A C++ excepLlon handler ls a cotcb cloose whlch has
Lhree parLs 1 Lhe keyword caLch 2 Lhe declaraLlon
wlLhln parenLheses 3 a seL of sLaLemenLs wlLhln a
compound sLaLemenL
W lf Lhe caLch clause does noL conLaln a reLurn
sLaLemenL Lhe execuLlon of Lhe program conLlnues
aL Lhe sLaLemenL LhaL follows Lhe lasL caLch clause ln
Lhe llsL
W 1he C++ excepLlon mechanlsm ls sald Lo be
noresumptive once Lhe excepLlon has been handled
Lhe execuLlon of Lhe program does noL resume
where Lhe excepLlon was orlglnally Lhrown
Exception Objects
W 1he caLch clause can be elLher a Lype declaraLlon or an ob[ecL
declaraLlon
An ob[ecL declaraLlon should be used when lL ls necessary Lo
a) obLaln Lhe value or b) manlpulaLe Lhe excepLlon ob[ecL
lor Lg leL us change Lhe deslgn of pushCnlull excepLlon class Lo
sLore Lhe value whlch could noL be pushed on Lo Lhe sLack
class pushOnFull{
public:
pushOnFull (int i) : _value(i) { }
int value() {return _value}
private:
int _value;
}
void iStack::push(int value)
{
if (full())
throw pushOnFull(value):
..
..
}
%he class pushOnFull has a new member function value() that can be used in the catch
clause to display stored in the exception object
catch (pushOnFull eObj){
cerr << "trying to push the value " << eObj.value() << "on a full stackn; }
%his can be reference type also, i.e., &eObj
Exception Objects
W An excepLlon ob[ecL ls always creaLed aL Lhe Lhrow polnL even
Lhough Lhe Lhrow expresslon ls noL a consLrucLor call
enum EHstate {noErr, zeroOp, negativeOp, serverError};
enmu EHstate state = noErr;
int mathFunc(int i){
if (i == 0){
state = zeroOp;
throw state; //Exception object created
}
// Otherwise normal operation
}
n the example on the
RHS, the exception object
of type EHstate is created
by throw expression and
initialized with the value of
the global object state
%he exception declaration of a catch clause behaves very much like a parameter
declaration. When the catch clause is entered, if the exception declaration declares an
object, this object is initialized with a copy of the exception object
void calculate (int op){
try{
mathFunc(op);
}
catch (EHstate eObj) { .} // eObj is a copy of the
// exception object
}
%he exception decleration
in the example on RHS
resembles a pass-by-
value parameter.
%he catch clause can
directly ref. excp. obj
&eObj
Expectation Handling Stack Unwinding
W 1he search for a catch c|ause to hand|e a thrown except|on proceeds as
fo||ows
W f the throw except|on |s |ocated w|th|n a try b|ock the catch c|auses
assoc|ated w|th th|s try b|ock are exam|ned to see |f there |s a
hand|er
W f the catch c|ause |s not found the search cont|nues |n the ca|||ng
funct|on and |f the ca|| to the funct|on ex|t|ng w|th the except|on |s
w|th|n a try b|ock the search for the correspond|ng hand|er |s
performed
W 1h|s process cont|nues up the cha|n of nested funct|on ca||s unt|| a
catch c|ause for the except|on |s found
W |se the program ca||s the term|nate() funct|on def|ned |n the C++
standard ||brary 1he defau|t behav|or of term|nate |s to ca|| abort()
W 1he process by wh|ch compound statements and funct|on def|n|t|ons ex|t
because of a throw except|on |n the search for a catch c|ause for
hand||ng the except|on |s ca||ed stack unw|nd|ng
W C++ guarantees that as the stack |s unwound the destructors for |oca|
c|ass ob[ects are ca||ed even though the|r ||fe t|me ends due to an
except|on thrown
Expectation Handling Rethrow
W lL ls posslble LhaL a slngle caLch clause can noL compleLely
handle an excepLlon A caLch clause can pass Lhe excepLlon Lo
anoLher caLch clause furLher up Lhe llsL of funcLlon calls by
reLhrow Lhe excepLlon
A reLhrow expresslon has Lhe form
throw
catch (exception eObj){
if (canHandle (eObj))
// handle the exception
return;
else
throw;
}
enum EHstate {noErr, zeroOp, negativeOp, serverError};
void calculate (int op){
try{
mathFunc(op); // exception thrown with zeroOp
}
catch (EHstate eObj) {
eObj = severeErr; // rethrow with value modified
throw;
}
}
Expectation Handling %he Catch-All Handler
W A funcLlon may wanL Lo perform some acLlons before lL exlLs wlLh a Lhrow excepLlon
even Lhough lL can noL handle Lhe excepLlon LhaL ls Lhrown
such as release of resources eg llle opened or dynamlc memory goLLen %or)
unlocklng of a locked resource
W 8aLher Lhan provldlng a speclflc caLch clause LhaL mlghL be Lhrown for dolng a Lhlng llke
release of resources we can employ a catcha|| clause
W 1he caLchall clause has an excepLlon declaraLlon of Lhe form () where Lhe Lhree doLs
referred Lo as an e|||pse
void manip(){
resource res;
res.lock();
try{
// use res
// some action caused ex.
}
catch (.){
res.release();
throw;
}
try{
stack.display();
for (int ix = ; ix < 5; ++ix){
// push / pop operations (ref. the ex. Earlier)
}
catch (pushOnFull) { }
catch (popOnEmpty() { }
catch (.) { } // must be last catch clause
A catch(.) clause can be used by itself or in
combination with other catch clauses
Expectation Specifications
W 1he declaraLlons of push%) and pop%) funcLlons of Lhe class lSLack ln our
examples sofar do noL provlde any lndlcaLlon of Lhe klnd of excepLlons Lhey
Lhrow
Cne posslble soluLlon ls Lo add a commenL assoclaLed wlLh Lhe declaraLlon
of each member funcLlon
class iStack{
public:
// ...
void pop(int &value);
// throw popOnEmpty
void push(int value);
// throw pushOnFull
private:
// ...
};
class iStack{
public:
// ...
void pop(int &value); throw (popOnEmpty);
void push(int value); throw (pushOnFull);
private:
// ...
};
xception Specification provides a mechanism to list
the exceptions a function may throw with the function
declaration.
An exception declaration is part of the function
interface and it is a contract between the function
and rest of the program
Powever Lhls does noL
lnform Lhe compller Lo
guaranLee LhaL no oLher
klnds of excepLlons are
Lhrown
1he excepLlon declaraLlon wlll have Lo be speclfled each
Llme Lhe funcLlon ls redeclared
Lg exLern lnL foo %lnL l 0) Lhrow %sLrlng)
Expectation Specifications
W LxcepLlons are runLlme anomalles 1herefore lL ls noL posslble Lo know aL
complleLlme all Lhe posslble excepLlons LhaL may occur and enforce Lhe
excepLlon speclflcaLlons
1herefore lf a funcLlon Lhrows an excepLlon noL speclfled Lhe funcLlon
unexpecLed%) deflned ln Lhe sLandard C++ llbrary ls lnvoked whlch ln Lurn
may call LermlnaLe%)
An exception specification can also be provided in the declaration of a pointer to a
function.
void (*pf) (int) throw (string);
Exceptions and Design ssues
Exception handling should be used to communicate anomalies between
parts of program that are developed independently.
For Eg., a library implementer may decide to use exceptions
%hrowing an exception is not as fast as normal function call
Programmers should also consider using normal error handling techniques
such as returning an error code
Classes
W C|asses are a C++ mechan|sm for user to def|ne own data types
W Def|n|t|on
c|ass def|n|t|on has 2 parts
1 C|ass head composed of keyword c|ass fo||owed by the
c|ass name
2 C|ass body enc|osed by a pa|r of cur|y braces
4 J|th|n the c|ass body the c|ass data members and
member funct|ons and the access |eve|s of the
members are spec|f|ed
c|ass body def|nes the scope of the members
ach c|ass def|n|t|on |ntroduces a d|fferent c|ass type s such
two c|ass types even |f they have the same member ||st are
d|fferent
class First {
int ival;
double dval;
};
class Second{
int ival;
double dval;
};
class First obj; // way , from C
Second obj ; // way
Class type can be ref. to in two ways: . Specifying the key word class followed by the
class name, . Only specifying the class name
obj = obj; // invalid
Classes Data Members
W C|ass data members can be def|ned |n the same way var|ab|es
are dec|ared
c|ass data member can be of any type
c|ass data member can be of type nonstat|c and stat|c
Jh||e data member dec|arat|ons are very much s|m||ar to
var|ab|e dec|arat|ons |n a b|ock scope or namespace
scope w|th one d|fference that a data member can not be
|n|t|a||zed exp||c|t|y |n the c|ass body
C|ass data members are |n|t|a||zed us|ng c|ass constructors
#include <string>
class Screen {
int ival = 0; // invalid
string _screen;
string::size_type _cursor;
short _height; // it is also possible to declare as short _height, _width;
short _width;
};
Classes Member Functions
W set of operat|ons that user wants to do on the ob[ect are |mp|emented |n the form of
c|ass member funct|ons
Member funct|ons of a c|ass are dec|ared |ns|de the c|ass body
1he def|n|t|on of a member funct|on can a|so be p|aced |ns|de the c|ass body
Member funct|ons are d|st|ngu|shed from ord|nary funct|ons by the fo||ow|ng
propert|es
1 Member funct|ons are dec|ared w|th|n the scope of the|r c|ass Mean|ng the
name of a member funct|on |s not v|s|b|e outs|de the scope of |ts c|ass
2 Member funct|ons have fu|| access pr|v||eges to both the pub||c and pr|vate
members of the c|ass whereas ord|nary funct|ons have access on|y to the
pub||c members of a c|ass
member funct|on |s referred to us|ng the dot or arrow member access operator
as |n
ptrcreenhome()
mycreenhome()
class Screen {
pubic:
void home(); { _cursor = 0;}
void move(int, int);
char get(); { return _screen[_cursor];}
char get(int, int);
void checkRange(int, int);
Classes Member Access
W Jhen member funct|ons of a c|ass are re|mp|emented |f the
|nterface |s same the code that |s us|ng these funct|ons need
not be re|mp|emented
W nformat|on n|d|ng |a a forma| mechan|sm to prevent the
funct|ons of a program to access d|rect|y the |nterna|
representat|on of a c|ass 1he access restr|ct|ons to the c|ass
members |s spec|f|ed by the key words
1 pub||c
2 pr|vate
3 protected
class Screen {
pubic:
// member functions
private:
static const int _height = 4;
static const int _width = 80;
string _screen;
string::size_type _cursor;
};
OC
AsslgnmenL 1
Submlsslon %on or before) CcL 21
sL
2011
noLe 1he funcLlons / program should complle and execuLe
wlLhouL errors besldes performlng Lhe asked Lask
1 %Lxerclse 313) WrlLe a small funcLlon / program Lo read a
sequence of sLrlngs from a sLandard lnpuL unLll elLher Lhe same
word occurs ln successlon or all Lhe words have been read use
a whlle loop Lo read Lhe LexL one word aL a Llme use Lhe break
sLaLemenL Lo LermlnaLe Lhe loop lf Lhe word occurs ln
successlon rlnL Lhe word lf lL occurs ln successlon or else prlnL
a message LhaL no word was repeaLed
2 uslng a swlLch sLaLemenL lmplemenL a program LhaL counLs Lhe
number of vowels blank spaces and Labs ln a glven sLrlng whlch
ls glven as lnpuL from a sLandard lnpuL rlnL Lhe number of
occurances of each vowel space and Lab on sLandard ouLpuL

S-ar putea să vă placă și