C Training Material

download C Training Material

of 179

Transcript of C Training Material

  • 7/27/2019 C Training Material

    1/179

    Basics of C/C++ & Windows

    Programming to learn COM

    (Note: This document does not cover C/C++ or SDK & VC++ in detail. This is only adocument made to give one enough no!ledge to "roceed !ith #indo!s $rogramming

    !ith C/C++ and then C%.The contents o' this document are retrived 'rom various

    oos and !e "ages and modi'ied to suit the re)uirement.*

    By

    Network Solutions Ltd.

    Koramangala

    Banglore

    Contents

    ntroduction to the $rogramming ,anguage C-istory %' CNature

    C as a second generation and third generation ,anguage

  • 7/27/2019 C Training Material

    2/179

    sage ,ooing at C 'or the irst Time

    Com"iling 01uilding and #arning essages Ste"s to Create a C a""lication

    Some Theory aout Com"iling and ,ining$rinting moe than one line

    Data declarationSome comments aout CommentsThe 2rammer o' C34ercise5 'e! de'initions and Termsunctions

    %%$S (%6ect %riented $rograming Systems*$rocedural0 Structured and %6ect %riented $romming%6ectClass3nca"sulation5straction

    #hy C++

    5 com"arison o' C and C++ntoduction#hy is C++ etter than CStreams3sca"e Se)uences#hat is a $ointerThe ndirection and 5ddress%' %"eratorsunctionsStructures3numerationsClass

    3nca"sulationnline unctions$olymor"hismnheritance

    Dynamic ,ining5$s and emory odelsThreading#indo!s $rograming in C (SDK*

    5n ntroducton to nicode#ide Characters and #indo!s

    #indo!s and essages 5 #indo! o' %ne7s %!n The #indo!s $rogramming -urdles 5n 34ercise in Te4t %ut"ut $ainting and 8e"ainting

    The #9$5NT essage

    5n ntroduction to 2D1asic Dra!ingThe Structure o' 2DThe Device Conte4t

  • 7/27/2019 C Training Material

    3/179

    Dra!ing Dots and ,inesChild #indo! Controls

    nstructions or the aculty

    ntroduction to the $rogramming ,anguage C ;hrs-istory %' CNature

    C as a second generation and third generation ,anguagesage

    ,ooing at C 'or the irst TimeCom"iling 01uilding and #arning essagesFor the Rest of the section give a Demo

    Ste"s to Create a C a""licationSome Theory aout Com"iling and ,ining

    $rinting moe than one line Data declaration

    Some comments aout CommentsThe 2rammer o' C34ercise5 'e! de'initions and Termsunctions

    %%$S (%6ect %riented $rograming Systems* (hrs$olymor"hismnheritance

    Dynamic ,ining5$s and emory odels =hrsThreading

  • 7/27/2019 C Training Material

    4/179

    #indo!s $rograming in C (SDK*

    5n ntroducton to nicode#ide Characters and #indo!s

    #indo!s and essages 5 #indo! o' %ne7s %!n

    The #indo!s $rogramming -urdles ;.? hrs %nly a5n 34ercise in Te4t %ut"ut Demo and @5

    $ainting and 8e"aintingThe #9$5NT essage5n ntroduction to 2D1asic Dra!ingThe Structure o' 2DThe Device Conte4tDra!ing Dots and ,inesChild #indo! Controls

    MFC ------------------------------------------------- hrsCOM -------------------------------------------------!"hrs

  • 7/27/2019 C Training Material

    5/179

    #ntrod$ction %o Programming ang$age C

    'istor( of CThe milestonesin C7s develo"ment as a language are listed elo!:

    NA develo"ed c. =BB D3C $D$ 5ssemly ,anguage

    1C$, a user 'riendly %S "roviding "o!er'ul develo"ment tools develo"ed 'rom

    1C$,. 5ssemler tedious long and error "rone.

    5 ne! language EE177 a second attem"t. c. =BF.

    5 totally ne! language EEC77 a successor to EE177. c. =B=

    1y =BG NA %S almost totally !ritten in EEC77.

    )at$re

    C as a second generation and third generation lang$age

    The C language "ossesses the "o!er'ul lo!level 'eatures o' second generation languages lie"ointers0 memory allocation0 it mani"ulation etc. t also su""orts conditional constructs0 loo"constructs0 a rich set o' o"erators and a variety o' data structures as in third generation languages.

    The comined 'eatures o' second and third generation languages mae C language a very"o!er'ul and a 'le4ile language. These 'eatures o' C language mae it "ossile to use thelanguage 'or Systems "rogramming0 lie develo"ment o' Com"ilers0 nter"reters0 %"eratingSystems0 2ra"hics and 2eneral tilities and also the 'or the host o' a""lications in commercial

    environment.

    *sage

    ooing at C for the First %imeThereHs something to e said 'or starting !ith sim"le e4am"les. 5 la!yer0 e4"laining a conce"tto a "erson !ith no no!ledge o' the la!0 !ould do !ell to egin !ith an elementary e4am"lerather than hitting the lay"erson !ith years o' legal training at once. The lay"erson doesnHt "ayto e im"ressed0 ut to understand his or her "rolems etter.,earning aout "rogramming is no di''erent. ThatHs !hy !eHll start !ith the sim"lest e4am"leyou can imagine. To mae it even easier0 letHs loo at the 15SC version 'irst:$8NT I-ere amJI

    This statement0 in case you havenHt seen it e'ore0 constitutes a com"lete "rogram in 15SC.oreover0 it actually "rints something0 so you can veri'y that it !ored.-ereHs ho! the same "rogram loos in C:main (* "rint'(I-ere amJI*LM' youHre relatively ne! to "rogramming (though assume youHve "roaly seen 15SC e'ore*0the 'irst thing you need to no! is that these e4am"les suggest a larger "attern o' sim"le

  • 7/27/2019 C Training Material

    6/179

    "rograms. #ithin these "atterns are0 elieve it or not0 vast "ossiilities. The "attern 'or thesim"le 15SC "rogram is:$8NT Iyour9te4t9hereI-ere Hm introducing a convention Hll use throughout the oo: !ords in italics re"resentsomething that you "rovide. ou could ty"e any comination o' characters you !anted !here

    your9te4t9here is indicated.The C version is:main (* "rint'(Iyour9te4t9hereI*LMSo0 'or C0 another e4am"le that 'ollo!s this "attern is:

    main(* "rint'(I$rogramming0 it sounds lie 'un.I*L

    M

    #hen you ty"e in this short "rogram0 you should e care'ul aout the 'ollo!ing matters:O Ca"italiPation counts. %r rather0 in this case0 lac o' ca"italiPation counts. 15SC"rogrammers0 'or some reason no one understands0 o'ten leave the C5$S ,%CK ey on0 ut it!ould mae no di''erence i' they al!ays le't ca"italiPation o''. #ith C0 youHll )uicly 'ind thatty"ing Q$8NTR or Q$rint'R instead o' Q"rint'R results in an un'riendly error message.

    O $unctuation also counts. The 'irst mistae that a!aits you i' youHre coming 'rom 15SC or%8T85N is to 'orget the semicolon (L* at the end o' a statement. 5t least C is sim"ler in thisres"ect than $ascal: you al!ays terminate a statement !ith a semicolonL you donHt have to guess

    !hether or not to use one. -o!ever0 this rule doesnHt mean that you "ut one a'ter the terminatingrace (L*. (#eHll s"end more time !ith semicolons and statements later0 in case youHre thirsting'or more no!ledge on these esoteric su6ects.*O 8ememer also that doule)uotation mars (I*0 not single0 are re)uired.O S"acing does not count. ou can "ut any numer o' e4tra s"aces around the "arentheses andraces0 i' you !ant0 or even ty"e everything on the same line. %' course0 you canHt "ut s"aces inthe middle o' individual !ords0 turning Q"rint'R into Q"r int '0R 'or e4am"le. 5nd s"acing mattersto some e4tent in the te4t inside the )uotation mars0 ecause the te4t you enter there !ill e"rinted as you entered it0 letter 'or letter.

    -ereHs the "rogram one more time0 !ith slightly di''erent s"acing:

    main( * "rint'( I$rogramming0 it sounds lie 'un.I *LM

    ' all goes !ell !hen you enter and run the "rogram0 it !ill "rint the te4t string sans )uotationmars:$rogramming0 it sounds lie 'un.

  • 7/27/2019 C Training Material

    7/179

    5ssuming that this !ors0 you might try redoing the "rogram !ith di''erent strings. ' you have"rolems0 revie! the "receding "aragra"hs 'or "ossile mistaes in entering the "rogram. oualso might need to mae sure that youHre using your com"iler to correctly uild an a""lication.

    5 e! #ords aout Com"iling0 1uilding0 and #arning essages

    5lthough it may sound hardhearted0 in this oo Hll o''er only limited hel" in using a Ccom"ilerthat is0 the so't!are you uy to translate and run your "rogram. 3ach C "acage hasits o!n commands and idiosyncrasies0 and each comes !ith its o!n instruction manual thatought to e the est guide to use o' commands. ortunately0 the language itsel' (ho! you actually!rite the "rogram* has a standard that is more or less universally adhered to aside 'romoccasional e4tensions.-o!ever0 there are a 'e! things that can e said aout the "rocess o' com"iling. Together withlinking, the process of compiling a program and getting it ready to run is called building.

    Try out $lease

    ' youHre using icroso't Visual C++0 !hich re'er to ecause it is one o' the standard com"ilersin use today0 the ste"s you tae are sho!n in the list that 'ollo!s. ou !ould 'ollo! roughly thesame ste"s !ith other com"ilers0 although the menus and e4act command names may edi''erent. Note that although QC++R is in the "roduct name0 the com"iler is "er'ectly ca"ale o'acting as a straight C com"iler6ust mae sure you give your source 'iles a .C e4tension0 and thecom"iler !ill use the rules o' the C language rather than C++. !ould e4"ect other C/C++"acages to ehave in a similar !ay.

    5nother thing recommend0 i' you are using Visual C++ in the #indo!s environment0 is toselect Console a""lication (i' running #indo!s NT* or @uic#in (i' running in the =it

    environment* as the "ro6ect ty"e. 1oth o' these ty"es o' a""lications "rint directly to the screen!ithout 'orcing you to !orry aout all the e4tra details o' managing a #indo!s a""lication.(ThatHs a su6ect 'or another oo.*The ste"s 'or com"iling and lining are:

    =. 5'ter entering a "rogram0 save it as a source 'ile !ith a .C e4tension ('or e4am"le0 -.C*.;. Create a ne! "ro6ect and select Console or @uic#in as the a""lication ty"e. 5dd the source'ile (-.C* to the "ro6ect.G. rom the $ro6ect menu0 choose 1uild.>. rom the $ro6ect menu0 choose 8un.' you got stuc on ste" G0 you encountered either a com"iler error or a liner error or oth. 5

    com"iler error indicates that something !as !rong in the !ay you ty"ed in the "rogramL "erha"syou 'orgot to ty"e in the semicolon (L* or one o' the )uotation mars (I*. 5 liner error0 at this"oint0 "roaly indicates that something in the develo"ment environment !as not set u"correctly. Chec your manual to mae sure that you installed the "roduct correctly.

    '0 ho!ever0 you ty"ed in the "rogram and 'ollo!ed all the ste"s correctly0 instead o' errormessages you "roaly received a cou"le o' !arning messages. 5t this "oint0 donHt "anic i' yougot !arning messagesL thereHs a ig di''erence et!een !arnings and errors. #arning messagesdonHt sto" you. 5s long as you got only !arning messages0 you can run the "rogram.

  • 7/27/2019 C Training Material

    8/179

    1ut you may !ant to get rid o' the !arning messages any!ay0 and 'or a good reason: !arningmessages are there to alert you that something une4"ected may e ha""ening. Not much can go!rong !ith this "articular "rogram0 ut in a larger "rogram0 a !arning can easily catch thesource o' a "otential error. ou may as !ell get in the hait o' trying to eliminate causes o'

    !arnings. n the !orld o' "ro'essional develo"ment0 testers donHt certi'y that a uild is correctunless it com"letes !ith Pero !arnings and Pero errors.

    ' youHre running Visual C++0 version =.F0 !ith the standard environment settings0 you got these!arnings:!arning C>F=G: 7"rint'7 unde'inedL assuming e4ternreturning int!arning C>FG?: 7main7 : no return value

    The 'irst !arning message tells you that the "rint' 'unction has no return value0 so the com"ilerassumes an integer (int* return value y de'ault. T!o things aout this 'act may e sur"rising.

    irst0 C has no conce"t o' a statement or suroutine the !ay that 15SC and %8T85N do. 5llroutines are 'unctions0 and every 'unction returns a value. n this "rogram0 "rint' is a 'unction!hose return value is ignored. (n C0 you can al!ays ignore return values i' you choose.* The'ollo!ing directive0 added to the eginning o' the "rogram0 clears u" the "rolem:include Ustdio.hThe include directive causes the com"iler to read in a 'ile that "ro"erly declares "rint'. 5t this"oint0 you may e "rotesting that it shouldnHt e necessary to declare such a 'unction e'oreusing it. 5'ter all0 it isnHt necessary !ith the $8NT statement in 15SC. 1ut C is di''erent. Thenumer o' ey!ords in C is e"t )uite small0 and "rint' is not a ey!ordL itHs 6ust another'unction !ith no s"ecial status. 5s it ha""ens0 "rint' is e4tremely use'ul and is there'ore "rovidedin every standard C lirary. 1ut you could 'reely re!rite or rede'ine "rint' i' you choose to0 and

    the com"iler itsel' doesnHt no! anything aout it. This as"ect o' C may e a slightinconvenience 'or no!0 ut it ultimately maes C much more com"act and 'le4ile. or all thesereasons0 the com"iler e4"ects you to declare "rint' e'ore you use it. 5s mentioned0 the stdio.hheader 'ile taes care o' this declaration.

    N%T3: 5 directive is not )uite the same thing as a statement0 although they may loosimilar. %ne critical di''erence is that a directive does not end !ith a semicolon (L*.

    There is e4actly one 'unction !ith s"ecial status to C itsel': the main 'unction. ou must have amain 'unction some!here 'or your "rogram to actually do anything0 ut e4ce"t 'or that0 mainoeys all the asic C "rinci"les a""lying to 'unctions.So main should return a value too0 shouldnHt itW This is true0 and it e4"lains the second !arning:main has no return value. The !ay to clear u" this "rolem is to "recede main !ith the ey!ordvoid0 !hich tells the com"iler not to e4"ect the 'unction to return a value:void main(* 3arlier stated that every 'unction must return a value0 ut void 'unctions are the e4ce"tion. Thecom"lete !arning'ree "rogram is no!:include Ustdio.h

  • 7/27/2019 C Training Material

    9/179

    void main(* "rint'(I$rogramming0 it sounds lie 'un.I*LM

    ,ome %heor( of Comiling and ining

    t !ould e nice i' "rograms ran y magic0 ut 'irst they have to e com"iled and lined. This istrue 'or a numer o' reasons0 !hich Hll tae some time to e4"lore here.If youre alreadycomfortable with the concept of language translators, you can safely skip to the next section.

    You can also skip this section if you dont like theory.

    There is no availale !ay to !rite "rograms directly 'or most com"uters0 using their nativelanguage. $rograms have to 'irst e translated into inary code that the com"uter can e4ecute.3ven assemly language0 !hich conce"tually is nearly the same thing as machine language0 hasto e translated. or e4am"le0 the assemly language instruction

  • 7/27/2019 C Training Material

    10/179

    code. The resulting "rogram runs 'aster and taes u" less s"ace. ouHll have to !ait !hile thecom"iler translates your "rogram0 ut the !ait is 'or a good reason.The second chicenandegg "rolem is this: ho! can anyone create a translator in the 'irst"lace0 i' no one ever !rites directly in machine languageW This "rolem is similar to the'ollo!ing "rolem in economics: i' nothing can e uilt 'rom scratch and i' every tool re)uires

    the e4istence o' another tool in order to e uilt0 then ho! did our industrial society ever come toe4istW This is the 'amiliar 1ootstra" "rolem: ho! do you get startedW 1ut the ndustrial8evolution did ha""en0 and a similar revolution has een going on !ith com"uters. 3ssentially0!henever a ne! chi" is introduced0 the manu'acturer maes sure that a rudimentary assemlerand systems so't!are are availale. This initial software may be generated on anotherpreviously existing computer. (This is called crossplatform development.!ltimately0 you cantrace the lineage o' all so't!are ac to a time !hen "eo"le really did !rite in machine code and'ed it into a dinosaur in the 'orm o' "unch cards.

    The 'inal stage in uilding a "rogram is usually lining. ,ining is the "rocess o' ringingtogether your "rogram module !ith code 'rom lirariesL this is !hat maes it "ossile 'or you to

    call the "rint' 'unction. n addition0 i' you rea your "rogram into multi"le moduleses"eciallyuse'ul 'or multi"rogrammer "ro6ectsthe "rocess o' lining connects these modules andcom"letes 'unction calls et!een the modules. ,iner errors tend to occur !hen a 'unctionre'erred to in one module is not de'ined any!here else or is de'ined in a !ay that is inconsistent!ith ho! it !as used. %'ten0 you clear u" a liner error y maing sure that a lirary is in theright directory or that the environment variales are correctly set.The ottom line is that a'ter you !rite a "rogram0 there is a !ait !hile the com"iler e4aminesyour "rogram 'or correctness and translates it. 1ut there are good reasons 'or having to !ait.No! itHs time to get ac to creating "rograms.

    Printing More than One ine

    The aility to "rint only one line is much too limiting0 so letHs add the aility to "rint multi"lelines. irst0 Hll introduce you to a 'unny character0 the ne!line. n C notation0 it loos lie this:\n

    )O%01 DonHt 'orget that this se)uence uses a acslash (Y*0 not a 'or!ard slash (/*.ThatHs the mistae made the 'irst =F times tried !riting a C "rogram.

    The acslash is CHs !ay o' re"resenting a s"ecial character inside a string o' te4t. Some o' thes"ecial characters include the ne!line (Yn*0 the ta (Yt*0 and emedded )uotation mars (YR*. 5acslash indicates that the character to 'ollo! has s"ecial meaning. ,o what do (o$ do if (o$want to rint an act$al acslash2 %he answer is1 $se two acslashes 3445. T!o acslashesresult in "rinting one acslash0 'our acslashes result in "rinting t!o0 and so on.1y "utting Yn inside a string0 you cause the "rint' 'unction to advance to the ne4t line !hereindicated. or e4am"le0 the 'ollo!ing "rogram starts a ne! line a'ter each line o' te4t is "rinted:#include

    void main (){ printf("Line 1\n"); printf("Line 2\n");

  • 7/27/2019 C Training Material

    11/179

    printf("Last line");

    %ne thing that may sur"rise you is that ecause Yn is a character lie any other0 you can 'reelyemed it inside a te4t string. The 'ollo!ing "rogram "rints the same results:#include

    void main() { printf("Line1\nLine2\nLast line");

    ou can even doules"ace0 i' you !ant to:#include

    void main() { printf("Line1\n\nLine2\n\nLast line");

    t should e clear !hat is going on at this "oint. 5s the "rint' 'unction reads each character that is

    not a acslash0 it out"uts the character to the terminal as is. '0 ho!ever0 it reads a acslash0 itinter"ets the ne4t character as a s"ecial character. #hen an QnR 'ollo!s the acslash0 it causesout"ut to start on a ne! line. (5nother !ay o' saying this is to say that "rint' generates a carriagereturn.* ' there is te4t remaining in the string0 "rint' continues reading characters normally.1y the !ay0 itHs common "ractice to terminate every lineeven the last!ith a ne!line (Yn*0unless you no! that the ne4t in"ut or out"ut is to continue on the same line. #ith this a""roach0the 'irst e4am"le in this section !ould e re!ritten as:#include

    void main (){ printf("Line 1\n");

    printf("Line 2\n"); printf("Last line\n");

    Data Declaration and )$mer Cr$nching

    To do anything use'ul in C0 you need to de'ine variales. ' you have ever used any other"rogramming language0 you no! that a variale is 6ust a "lace in memory that stores a value 'oryou.5ny variale you use must 'irst e declared0 ecause C needs to no! !hat ind o' data youHrestoring and ho! much s"ace to allocate in memory. ost "rogramming languages re)uiree4"licit declaration0 although a 'e! (such as 15SC* let you declare variales y de'aultL i' youuse a variale !ithout declaring it0 15SC maes assum"tions aout the ty"e and attriutes o'the variale.1ut in com"uter "rogramming0 as in li'e0 relying on assum"tions is dangerous. C has no de'aultdeclarations0 and C "rogrammers usually donHt mind the small amount o' additional !or thatthis maes necessary.The 'ollo!ing three lines o' code gives e4am"les o' C data de'initions ('or no!0 donHt !orryaout the di''erence et!een de'inition and declaration*:dou!le ;int count;int i $ emplo%ee#

  • 7/27/2019 C Training Material

    12/179

    These statements0 lie any other C statements0 are each terminated y a semicolon (L*. Theey!ords do$leand ints"eci'y data ty"esdoule"recision 'loating "oint and integer0res"ectively. (The di''erence et!een these ty"es is that the com"uter can mani"ulate integersmuch more e''iciently0 ut only 'loating"oint variales can store 'ractional )uantities.* Thenames 40 count0 i0 60 and em"loyee9num in the "receding e4am"le all ecome the names o'

    variales created y the de'inition. 34ce"t 'or 40 all the variales are integers.5n e4am"le "rogram should hel" clari'y this.#include

    void main(){ int i $;

    i ' 1; $ ' 2; printf("he sum of i and $ is d" i * $);

    This e4am"le introduces a very use'ul 'eature o' "rint': 'ormatted numer out"ut. The 'irstargument to "rint' is the 'ormat string:IThe sum o' i and 6 is ZdIThis is a )uoted string o' te4t in !hich most characters are "rinted literally ut some se)uenceso' characters have s"ecial meaning. T!ocharacter se)uences starting !ith a acslash (Y* areone ind o' s"ecial se)uence0 as !eHve seen. 5nother ind o' s"ecial se)uence consists o' thosestarting !ith the "ercent sign (Z*. Such se)uences "rint numers. S"eci'ically0 the meaning o'Zd is0 Q$rint the integer value o' the ne4t argument.R n this case0 that argument is the resultcalculated y adding the value o' i to the value o' 6:i + 6The "ractice o' com"uter languages varies 'rom standard 3nglish here. Note the "lacement o' the

    comma (0* in the com"lete statement:"rint'(IThe sum o' i and 6 is ZdI0 i + 6*LThe comma must a""ear a'ter0 not e'ore0 the second )uotation mar (I*. The role o' the commais to se"arate the t!o arguments0 and it must a""ear betweenthose arguments. n this case0 atleast0 the rule im"osed y the "rogramming language is a good deal more logical than 3nglish is.ou donHt "lace the comma inside the )uotation mars unless you intend 'or it to e "rinted.Commas can e used in oth !ays0 o' course. ou could "lace a comma inside the )uotationmars ecause you actually did !ant to "rint it. ouHd still need to "lace another comma outsidethe )uotation mars so that the arguments !ould e se"arated.ou can e4"eriment !ith much more interesting calculations here0 such as the 'ollo!ing'loating"oint calculation. Note that almost all 'loating"oint calculations assume that data ty"es

    and return values are do$le(doule "recision*0 !hich "rovides greater accuracy than single"recision (float*. 5nother thing to ee" in mind is that to "rint a 'loating"oint value0 you mustuse Z'0 not Zd. or e4am"le:include Ustdio.hinclude Umath.h

    void main(* doule a [ G.FL doule [ >.FL

  • 7/27/2019 C Training Material

    13/179

    doule cL

    c [ s)rt(a \ a + \ *L "rint'(IThe hy"otenuse [ Z'I0 c*LM

    This e4am"le introduces a cou"le o' ne! 'eatures !orth commenting on. irst0 the "rogram callsanother 'unction0 s)rt. ,ie "rint'0 s)rt is "rovided y the standard lirary. The math.h header 'ile"ro"erly declares the s)rt 'unction0 so math.h is included at the eginning o' the "rogram. ' s)rtis not declared0 C assumes that the 'unction returns an integer value0 !hich in 'act it does not(lie most math 'unctions0 s)rt returns a doule"recision 'loating"oint result*. This !ould e aserious "rolem ecause it !ould cause the com"uter to mae a mistae aout !hat ind o' datato "ass.

    )O%01 The s)rt 'unction taes the s)uare root o' its argument0 ut C "rogrammers a''ectionately re'er to this'unction as the Qs)uirtR 'unction.

    tHs al!ays good to declare all 'unctions e'ore using them. ' the 'unction is 'rom the standard Clirary0 thereHs a header 'ile availale !ith the a""ro"riate declaration. Documentation on lirary'unctions indicates !hich header 'ile to include.5nother 'eature introduced here is the use o' de'inition and assignment o' values in the samestatement. This assignment is actually initialization0 and it has some im"ortant restrictions:doule a [ G.FLdoule [ >.FLdoule cLThe variales a and are "ro"erly intialiPed !ith constant values. #hen you comine varialede'inition !ith the e)ual sign ([* this !ay0 the value assigned must e a constantL the com"ilermust e ale to determine !hat this value is at the time the com"iler reads the "rogram. The ne4tstatement0 !hich assigns a value to the variale c0 cannot e comined !ith a declaration0ecause the value on the right is not a constant:c [ s)rt(a \ a + \ *LThis may seem lie a lot o' rules0 ut it stems 'rom the 'act that the C language reuses o"eratorsvery e''iciently. #hen you de'ine a variale (such as a0 0 or c*0 you can give it an initial value0ut mae sure it is a constant. The use o' the e)ual sign ([* in other inds o' statements is muchmore 'le4ile. ou can "lace any variale on the le't side and any valid e4"ression on the right.The "revious line o' code0 !hich calcalates the value o' c0 is an e4am"le.

    ,ome Comments ao$t Comments

    No "rogramming language !ould e com"lete !ithout a 'acility 'or "lacing comments in the"rogram.t others me !hen "rogramming manuals say things such as QComments e4"lain the "ur"ose o'the code you !rite.R #ell0 thatHs not automatically true. The comment 'acility gives you theca"aility to include such e4"lanations0 ut you have to !rite them yoursel'. ' you !anted to0you could go craPy and "lace any !ords in comments0 even the !ords to Qary -ad a ,ittle,am.RThe com"iler asolutely does not care. -o!ever0 itHs certainly in your interest to "lacein'ormation in comments that may e hel"'ul to someone reading the "rogram.Technically s"eaing0 a comment consists o' te4t that the com"iler ignores. $eriod. The te4t you"ut there !onHt e evaluated as "art o' the C "rogram itsel'. et you really ought to usecomments ecause humansas !ell as com"uterso'ten have to read "rograms. 5s a "rogram

  • 7/27/2019 C Training Material

    14/179

    gro!s in com"le4ity0 you may not understand the "ur"ose o' a declaration or statement !rittenearlier0 even i' you !rote it yoursel'. The solution to this "rolem is to use a healthy dose o'comments and to say things that !ill e hel"'ul 'or someone looing at the code.C comments consist o' te4t et!een the symols /\ and \/. This te4t may occur on a single lineor can s"an multi"le lines. or e4am"le0 the last e4am"le in the "receding section could

    "ro'italy e commented as 'ollo!s:include Ustdio.hinclude Umath.h

    void main(*/\ Declare a0 0 and c as three sides o' a triangle0 in !hich a and are G and > units long. \/

    doule a [ G.FL doule [ >.FL doule cL

    /\ind hy"otenuse and "rint result. \/

    c [ s)rt(a \ a + \ *L "rint'(IThe hy"otenuse [ Z'I0 c*LM5gain0 the com"iler ignores all the te4t et!een /\ and \/. The e4act !ording and s"elling arethere'ore unim"ortant.

    %he 6rammar of C

    $rogramming0 i' you thin aout it0 is all aout "atterns. 5 "rogramminglanguage grammar is a

    set o' "atterns 'or "utting !ords and symols together to 'orm meaning'ul actions. #hen youunderstand the "atterns !ell enough0 you can use them to get the com"uter to do anything you!ant0 !ithin limitations.1ut !ithout some ind o' easy introduction to C0 looing at a "ure0 com"rehensive summary o'CHs grammar !ould e over!helming. or this reason0 !eHll start !ith "atterns around !hichyou can uild sim"le "rograms and then gradually add to their com"le4ity.The sim"lest "rograms 'ollo! this "attern:include&directives void main () { data_declaration_statements executable_statements

    include_directivesuse the 7incl$deey!ord to read header 'iles (the effect is the same as if youtyped the entire file right into your program code*. 5s mentioned earlier0 such header 'iles arenecessary ecause C doesnHt no! anything aout lirary 'unctions. t doesnHt no!0 'ore4am"le0 !hether the s)uare root 'unction (s)rt* returns an integer or a 'loating"oint result. Nordoes it no! ho! many arguments to e4"ect. The header 'iles0 such as stdio.h and math.h0"rovide this in'ormation. 34am"les o' 7incl$dedirectives are:#include #include

  • 7/27/2019 C Training Material

    15/179

    #include

    #hen you use a lirary 'unction0 such as "rint'0 consult C standardlirary documentation todetermine the corres"onding header 'ile to include. 5 header 'ile needs to e included no morethan one time0 regardless o' ho! many di''erent 'unctions re)uire it.8o$ ma( e wondering wh( these lines of code are called 9directives: and wh( the( don;t

    end with a semicolon. This is the ind o' distinction that can drive a novice craPy0 althoughe4"erienced C "rogrammers gro! used to it. The easiest0 most "ractical rule to rememer is thatany line eginning !ith a "ound sign (* is a directive0 and0 unlie statements0 directives are notterminated !ith semicolons.

    )O%01 n case youHre curious0 a directive is an instruction to the com"iler that controls ageneral condition during com"ilation. or e4am"le0 there are directives that a''ectre"orting o' error and !arning messages. 5 C statement0 in contrast0 either declares dataor is translated directly into an action that is "er'ormed !hen the "rogram is actuallyrunning. The distinction et!een statements and directives may seem aritrary0 es"eciallyecause there are some directives that can have im"ortant e''ects on "rogram ehavior. t

    may e easiest 'or no! 6ust to rememer that i' something egins !ith a "ound sign (*0itHs a directive.

    1y data_definition_statements0 re'er to variale de'initions you "lace in your "rogram.5lthough technically you donHt have to have variales0 virtually any "rogram that does anythinguse'ul has at least a 'e!. n C0 variale de'initions are statements0 and each must e terminatedy a semicolon (L*. The sim"lest data de'initions declare one variale each. The ty"e nameint0long0 or do$lein the 'ollo!ing e4am"les"recedes the variale name:dou!le ;dou!le %;dou!le h%potenuse;int total;int c;

    Variale declarations in C enale you to de'ine as many variales on the same line as you chooseas long as you se"arate the names y using commas. or e4am"le0 the 'ollo!ing e4am"lede'ines the same doule"recision 'loating "oint variales and integers that the "recedinge4am"le does. n the 'irst line0 40 y0 and hy"otenuse are all de'ined as having ty"e do$le0meaning that each variale stores doule"recision 'loating"oint data. The variales total and care integers.dou!le % h%potenuse;int total c;

    ou can also comine muli"le data de'initions !ith initialiPation:dou!le ,ei+ht ' -. hei+ht ' 1./;int i $ 0 ' 1;int a ' / ! c ' 2;

    inally0 y executable_statements re'er to the rest o' the "rogram. These statements tae somesort o' action during run time. Data de'initions0 in contrast0 donHt cause any actions !hile the"rogram is actually runningL they 6ust reserve s"ace.The distinction et!een data de'initions and e4ecutale statements is im"ortant0 ecause youmust "lace all data de'initions ahead o' all e4ecutale statementsthe t!o inds cannot e

  • 7/27/2019 C Training Material

    16/179

    intermingled. 34ecutale statements can do a lot o' things0 ut nearly all o' these things 'all intoone o' three ma6or categories o' actions:

  • 7/27/2019 C Training Material

    17/179

    angleC [ Calculate95ngle(angle50 angle1*5s youHll see in Cha"ter G0 you can use the same or di''erent variales !ithin the 'unctionde'initionthe code that de'ines !hat Calculate95ngle does. Some "urists insist on calling thevalues actually "assed arguments and the variales used in de'initions "arametersoralternatively0 actual arguments vs. 'ormal argumentsut !eHll stic !ith using arguments

    e4ce"t !here the distinction is critical.

    #nteger

    ou may recall 'rom highschool math that an integer is a !hole numer (no 'ractional "ortion*that can range into negative values as !ell as Pero or "ositive. This corres"onds e4actly !ith theconce"t o' integer (int* in C and other languages.2enerally s"eaing0 'loating"oint variales can hold any value that an integer can0 so !hy useintegers at allW The reason is that 'loating"oint math is much more com"le4. 5 C$ can o"erate'ar more e''iciently on an integer. oreover0 there are many cases in !hich a variale needs tohold a numer that !ill never e a 'raction. 3ver. 5n e4am"le is a variale used to count tri"sthrough a loo". ntegers are a much etter choice 'or data re"resentation in such cases.

    Floating-Point ?al$es

    loating"oint values can hold 'ractions. %ther languages o'ten re'er to 'loating"oint values asreals ('or real numers*0 and0 realistically s"eaing0 the terms can e used interchangealy. To"rovide ma4imum 'le4iility0 'loating"oint values are re"resented !ith a ind o' scienti'icnotation involving sign0 e4"onent0 and mantissa. ' you donHt rememer these terms 'rom school0thatHs %K0 ecause itHs all su""osed to e hidden 'rom you any!ay. The only thing to rememeris that it re)uires more com"uting "o!er 'or the "oor little C$ to handle 'loating "oint0although modernday math co"rocessors do hel". or o"timal results0 stic to integers as much as"ossile.

    ,ingle-Precision ?al$es

    5single"recision value in C is a 'loating"oint value stored in 'our ytes. Strangely0 variales o'this ty"e are declared !ith the 'loat ey!ord.

    Do$le Precision ?al$es

    5 doule"recision value (doule* in C is a 'loating"oint value stored in eight ytes. Thesevalues re)uire more s"ace ut "rovide sustantially more range and accuracy. 1ecause o' thenecessary conversion et!een decimal ('or dis"lay* and inary ('or internal storage*0 thereHsusually a loss o' "recision !henever 'ractions are involved. or this reason0 i' you are going todo 'loating"oint calculations0 doule "recision is much etter.

    0=ressions

    5n e4"ression is a single numer or variale0 or a comination o' variales0 numers0 ando"erators (such as +* that evaluates to a single value. The numeral ? is an e4"ressionL so is 4 + y.n C0 e4"ressions have an interesting relationshi" to statements (the asic unit o' e4ecution* asdescried in the ne4t section.

    0=ressions and ,tatements

    %ne o' the areas in !hich C most strongly de"arts 'rom other languages is in its conce"t o'e4"ressions. There are some "oints here that arenHt ovious0 and you need to understand them to'ully tae advantage o' C or to read C code.

  • 7/27/2019 C Training Material

    18/179

    n 15SC or %8T85N0 !hich are ty"ical o' most com"uter languages0 you can only assign avalue to only one variale at a time. or e4am"le0 the 'ollo!ing is a com"lete statement in either15SC or %8T85N:i [ 6 + =15SC and %8T85N use a single e)ual sign ([* to sho! assignment. C does the same. n

    $ascal0 youHd use the :[ symol instead:i :[ 6 + =$ascal also uses semicolons in its o!n "erverse 'ashion0 ut letHs not get into that.#ith all three languages15SC0 %8T85N0 and $ascalyou can loo at this e4"ression andno! that it 'orms a com"lete statement. 1ut !ith C0 the e)ual sign ([* is an o"erator lie anyother0 and it returns a value 6ust as o"erators such as +0 ]0 \0 and / do. This means that assignmentmay e "er'ormed in the middle o' a larger e4"ression.5n e4am"le should hel" clari'y. ou can !rite the same e4"ression in C as you can in 15SC or%8T85N0 ut the C version returns a valuenamely0 the value that !as assigned:i [ 6 + = /\ Value o' this e4"ression is 6 + = \/5nd hereHs !here !e can see the ig di''erence. 1ecause this assignment returns a value

    (namely0 6 + =*0 you can "lace the !hole thing inside a more com"le4 e4"ression: [ i [ 6 + =L#hat is this 'unnylooing constructW To understand it0 you 'irst have to understand that theassociativity o' assignment is righttole't0 !hich means that !hen more than one assignmento"erator ([* is involved0 the rightmost assignment is evaluated 'irst. Conse)uently0 the "recedinge4am"le is e)uivalent to: [ (i [ 6 + =*LThe sue4"ression i [ 6 + = does t!o things: it assigns the value o' 6 + = to i and then it returnsthe value that !as assignednamely0 6 + =. 8e"lacing the right side !ith 6 + = creates the'ollo!ing e4"ression: [ 6 + =L

    n other !ords0 a'ter i is assigned the value 6 + =0 that value is then assigned to . So oth and iare assigned the value o' 6 + =.,etHs loo at another e4am"le0 !hich uses a common coding techni)ue. This e4am"le assigns thevalue F to all 'our variales: a0 0 c0 and d.a [ [ c [ d [ FL5gain0 associativity is righttole't. There'ore0 this e4"ression is e)uivalent to:a [ ( [ (c [ (d [ F***L /\ 5ssign F to d \/The sue4"ression d [ F oviously assigns F to d. The return value o' d [ F is F0 !hich meansthat the "rogram acts as though d [ F !ere re"laced !ith F. The "rogram then evaluates thestatement as i' it !ere:a [ ( [ (c [ F**L /\ 5ssign F to c \/

    This causes F to e assigned to the variale c. The "rocess continues0 y successive ste"s:a [ ( [ F*L /\ 5ssign F to \/a [ FLSo a0 0 c0 and d all get the value F.The statement isnHt really eing re!ritten. The "rogram statements al!ays remain intact and cane e4ecuted re"eatedly (!hich can ha""en !hen you !rite a loo"*. #hatHs going on is that the Ccom"iler inter"rets the statement as though it !ere a series o' smaller statements.

  • 7/27/2019 C Training Material

    19/179

    ,etHs loo at one more e4am"le. 1ecause the e)ual sign ([* is an o"erator lie any other0 it cane comined !ith other o"erators0 such as addition (+*. or e4am"le0 assume that a0 0 and c areall integer variales:a [ = + ( [ = + (c [ GF**L /\ 5ssign GF to c \/The "rogram 'irst evaluates c [ GF0 !hich "laces GF into c and returns the value GF. The "rogram

    then "roceeds as i' the sue4"ression c [ GF !ere re"laced y its return value0 GF:a [ = + ( [ = + GF*L /\ 5ssign G= to \/No! the "rogram evaluates [ = + GF0 !hich "laces G= into and returns the value G=. The"rogram "roceeds as i' the sue4"ression [ = + GF !ere re"laced y the value G=:a [ = + G=L /\ 5ssign G; to a \/inally0 a is assigned the value G;.

    N%T3: n the "receding e4am"le0 "arentheses are necessary. 5lthough you can 'reely mi4 theassignment o"erator ([* !ith other o"erators0 the assignments must mae sense. C languagee4"ressions are governed y CHs rules o' "recedence0 !hich dictate that addition (+* is evaluatede'ore assignment ([*. Consider !hat !ould ha""en i' the "receding e4am"le had no

    "arentheses:a [ = + [ = + c [ GFL1ecause addition (+* has higher "recedence than assignment ([*0 this statement is e)uivalent to:a [ (= + * [ (= + c* [ GFLThis in turn "laces the sue4"ression (= + c* on the le't side o' an assignment:(= + c* [ GFThis last e4"ression clearly maes no sense and is e4"licitly disallowed ( r$les of Csynta4.There'ore0 !hen you mi4 assignment !ith other o"erations0 e sure to use "arentheses to clari'yorder o' evaluation.

    This 'le4iility in the use o' assignment has im"ortant im"lications 'or C synta4. 5ssignments

    are 6ust one o' the uilding locs o' e4"ressionsassignments donHt automatically 'ormcom"lete statements as they do in other languages.#hen does an e4"ression ecome a statementW ThatHs sim"le: !hen itHs terminated y asemicolon. 5n e4"ression terminated y a semicolon is the most common ty"e o' statement in C:e4"ressionLThis synta4 has some interesting conse)uences. t im"lies that any e4"ression can e terminated!ith a semicolon to 'orm a com"lete statement. Such e4"ressions donHt even have to involveassignment. -ereHs an e4am"le:4Li + 6Ltotal \ sum + ;L

    ?L;.FLou !ill liely never see these statements in a real C "rogram0 'or the good reason that theydonHt actually do anything. 1ut they are legal 6ust the same. 5s !ith all e4"ressions0 each o'these returns a value. 1ut !hen a statement is terminated y a semicolon0 the overall value o' thee4"ression is thro!n a!ay.#hat you !ill see0 and o'ten0 are e4"ressions in !hich a 'unctionHs return value is ignored. ore4am"le0 oth o' the 'ollo!ing are legal constructs:result [ Calc(a0 0 c*L

  • 7/27/2019 C Training Material

    20/179

    Calc(a0 0 c*Lou could !rite either statement de"ending on !hether you !anted to save the result o' the'unction. This is a nice convenience0 ecause some times you may care aout the result o' the'unction and other times you may not.

    N%T3: The 'irst statement in the "receding e4am"le is not legal i' the 'unction is declared void0although the second statement is al!ays legal.any 'unctions (o' !hich "rint' is a "rominent e4am"le* have side e''ects: they do more than6ust return a value. #hen a 'unction has side e''ects o' some ind0 a 'unction call can e use'uleven though it has no return value or that value is ignored.

    Ret$rning a ?al$e to the ,(stem

    The main 'unction can return a value 6ust as other 'unctions can0 de"ending on ho! you declareit. The value returned y main is "assed ac to the system or calling "rocess. 5n e4am"le o'!here such a return value might e used is in an SD%S atch 'ile. The value returned y the

    "rogram (its return code* can cause a 6um" to a ne! location !ithin the atch 'ile0 assuming thatthe 'ile is !ritten to test the "rogramHs return code.5s a rule0 a return code o' F indicates that the "rogram detected no "rolems. 1y convention0 anonPero return code indicates an error.The revised synta4 'or a "rogram is:include9directives

    int main (* data9declaration9statements e4ecutale9statements return e4"ressionL

    MStrictly s"eaing0 this synta4 isnHt asolutely "recise0 ut it gives you an idea o' !hatHs "ossile.5ctually0 the return statement can occur any numer o' times !ithin e4ecutale9statements0 andit doesnHt necessarily have to occur on the last line.5s a 'irst e4am"le0 the 'ollo!ing "rogram "rints out a message and returns F unconditionally0 toindicate sucess:include Ustdio.hint main(* "rint'(I-ello0 there.YnI*L return FLM

    ore ty"ical is the ne4t e4am"le0 !hich tests 'or an error condition (a Pero divisor* e'oredeciding !hether toreturn an error code:include Ustdio.hinclude Umath.h

    int main(* doule divisor0 )uotientL

    scan'(IZ'I0 divisor*L

  • 7/27/2019 C Training Material

    21/179

    i' (divisor [[ F* return =L )uotient [ =FF.F / divisorL "rint'(IThe )uotient is ZdYnI0 )uotient*L return FL

    MThis e4am"le introduces the use o' the C i' statement0 !hich in this case tests the value o' divisore'ore deciding !hether to return an error code. Note care'ully the use o' doule e)ual signs([[* to test 'or e)uality. i' (divisor [[ F* return =L#eHll see a lot more o' the i' statement in later cha"ters. The sim"lest 'orm o' the i' statementhas the 'ollo!ing 'ormat:i' (condition* statement should clari'y that condition is 6ust an integer e4"ression. 5n e4"ression evaluating to Pero

    means 'alsestatement is not e4ecuted!hereas everything else means true. This im"lies thatany integer e4"ression is valid in this conte4t. So you can !rite this: i' (=* return =L1ut this code !ould mean return ]= unconditionally0 !hich is silly0 i' you thin aout it0 ecauseit !ould e easier 6ust to ty"e:

    return =LThe i' statement loos harmless0 ut it has a 'e! "it'alls that a!ait you. 1y 'ar the !orst is the"ossiility o' mistaing the assignment o"erator ([* 'or the test'ore)uality o"erator ([[*. 1ecare'ulJ These t!o o"erators are very di''erent0 in !ays to e e4"lained later. or no!0 6ust maesure that you doule chec all tests 'or e)uality !ithin an i' condition to mae sure that doule

    e)ual signs ([[* are in use. There are times !hen you !ill !ant to use the assignment o"erator([* !ithin a condition0 ut they are much less common. or no!0 consider a single e)ual sign ([*!ithin a condition as a sure'ire indicator o' a ug.The i' statement is the 'irst e4am"le o' a control structure in this oo. 5 control structure is a"lace at !hich the "rogram may si" ahead or ac instead o' going to the ne4t statement. n thecase o' i'0 a condition that evaluates to 'alse causes the "rogram to si" over the statementimmediately 'ollo!ing the i'. 5 condition evaluating to true lets the "rogram e4ecute thatstatement.#eHll return to the su6ect o' control structures in detail0 ut 'irst letHs move to the allim"ortantto"ic o' 'unctions in C.

    F$nctions

    %ne o' the greatest aids in "rogramming is the use o' 'unctions. They can save you 'rom havingto ty"e common se)uences o' code over and over. They also let you organiPe your "rogram intological and coherent units.5 'unction de'ines ho! to carry out a s"eci'ic tas. %nce the tas is de'ined0 you can have itcarried out !herever you !ant0 sim"ly y calling the 'unction. ' youHve een 'ollo!ing allthrugh0 youHve seen e4am"les o' 'unction calls:

  • 7/27/2019 C Training Material

    22/179

    "rint'(I-i thereJYnI*Lscan'(IZdI0 &numer*L4 [ s)rt(;.F*LThe !ords "rint'0 scan'0 and s)rt re'er to 'unctions0 although only in the last case is the valuereturned y the 'unction actually used. n C0 a 'unction is a 'unction !hether or not it returns a

    value and !hether or not the value is used. There is no se"arate terminology such as "rocedure0suroutine0 or su"rogram.%' course0 Qsu"rogramR is a good !ay to suggest !hat 'unctions do. #hen a 'unction is called0control "asses to the 'unction as i' it !ere a se"arate "rogram. The com"uter then e4ecutes eachstatement in that 'unction until it either comes to the end o' the 'unction or encounters a returnstatement. n either case0 the 'unction is said to return. 5t that "oint0 control returns to the "lacein the "rogram !here the 'unction !as called.8eturn is an a""ro"riate term. t means that the "rogram goes ac to !here it !as e'ore the'unction !as called.Calls to 'unctions such as "rint'0 scan'0 and s)rt !or ecause these 'unctions are de'ined in the standard lirary.ou donHt need to su""ly de'initions 'or the 'unctions.

    ost C "rogrammers usually "lace the main 'unction 'irst0 'ollo!ed y the 'unctions that maincalls directly0 'ollo!ed y other 'unctions. This style o' "rogram organiPation is the to"do!na""roach.%he new s(nta= element here is f$nction@rotot(esA5 'unction "rototy"e "rovides ty"ein'ormation to the com"iler. ou can call a 'unction !ithout 'irst "roviding a "rototy"e0 ut thecom"iler !ould have to assume a de'ault return ty"e (int*0 and it !ould not e ale to checargument ty"es. 5s a rule0 you should al!ays include 'unction "rototy"es 'or each 'unction youcall.-ereHs the general 'orm 'or a 'unction "rototy"e:return9ty"e 'unction9name(arguments*LThe arguments consist o' a list o' argument declarationsL they are se"arated y commas i' thereare more than one. The declarations0 in turn0 consist o' a data ty"e 'ollo!ed y an argumentname:ty"e name0 ty"e name0 ...-ere are some e4am"les o' "rototy"es:=. Doule"recision result0 integer argument.doule ind8eci"rocal(int n*L

    ;. Doule"recision result0 three doule"recision arguments.doule @uadratic(doule a0 doule 0 doule c*L

    G. nteger result0 t!o integer and one doule"recision argument.int 8esetVars(int Ne!Start0 int Delta0 doule

    8atio*L

    The argument names have little "ur"ose in a "rototy"e e4ce"t 'or documentation. ' you !ant to0you can omit argument names 'rom "rototy"es. The 'ollo!ing declarations are e)uivalent to theones youHve 6ust seen:doule ind8eci"rocal(int*Ldoule @uadratic(doule0 doule0 doule*Lint 8esetVars(int0 int0 doule*LDe'ining the unction%nce again0 hereHs the 'unctionde'inition "art o' the synta4:return9ty"e 'unction9name ( arguments *

  • 7/27/2019 C Training Material

    23/179

    data9declaration9statements e4ecutale9statementsMThe e4ecutale9statements can include one or more return statements (assuming return9ty"e isnot void*:

    return e4"ressionLT!o things may strie you aout this synta4. irst0 it loos very similar to the synta4 'or themain 'unction. t should0 ecause the main 'unction is lie any other 'unction e4ce"t 'or a 'e!ey di''erences (mainly0 that it gets e4ecuted 'irst*. Second0 the 'irst line is almost the same as a'unction "rototy"e. or e4am"le0 here is a "ossile 'irst line o' a 'unction de'inition:doule ind8eci"rocal(int n* n 'act0 the eginning o' a 'unction de'inition is so close to the synta4 'or a "rototy"e that youcan save !or y co"ying the "rototy"e and "asting it into the de'inition.1ut there are a cou"le o' im"ortant di''erences et!een "rototy"es and de'initions:O 5 "rototy"e ends !ith a semicolon (L*0 ut in a 'unction de'inition0 an o"ening race (* 'ollo!sthe argument list. unction de'initions are not terminated y semicolons at all0 not even a'ter the

    'inal race (M*. ndividual statements inside the races !ill have semicolons0 ho!ever.O The argument name is not o"tional in a 'unction de'inition even though it is o"tional in"rototy"es.

    > Comlete 0=amle

    unctions donHt do anything until called y an e4ecuting "rogram. 3ven main has to e callede'ore it can e4ecutealthough in the case o' main0 the caller is the o"erating system.%nce !ritten0 a 'unction can e called any numer o' times.

    ou can use this techni)ue to create a more com"act version o' the "rogram:

    "ont worry #ead$n to understand the program

    include Ustdio.h

    int actorial(int n*L

    void main(* "rint'(IThe 'actorial o' G is ZdYnI0 actorial(G**L "rint'(IThe 'actorial o' > is ZdYnI0 actorial(>**L "rint'(IThe 'actorial o' ? is ZdYnI0 actorial(?**LM

    int actorial(int n* int result [ =L

    !hile (n =* /\ #hile n =0 result \[ nL /\ multi"ly y n decrement n \/ return resultLM

  • 7/27/2019 C Training Material

    24/179

    >rg$ments and More >rg$ments

    he 6actorial function ta0es a certain amount of li!ert% ,ithits ar+ument n7,hile (n > 1) 3 8hile n > 1

    result 3' n99; 3 multipl% !% n decrement n 3hese statements cause n to chan+e durin+ eecution of thefunction7 n is continuall% decremented until it is no lon+er+reater than 1. :o n is finall% reduced to 1.o, ,hat do %ou thin0 the follo,in+ statements doint emp1 emp2 ' -;

    emp1 ' 6actorial(emp2);printf("he value of emp2 is still d.\n" emp2);=f %ou put this code into a pro+ram and run it %oull find that

    it produces the follo,in+7he value of emp2 is still -.?o, can this !e he value of emp2 ,as passed to the ar+umentn and the function chan+ed the value of n to 1. 8h% didntemp2 chan+ehe ans,er is that the function +ets a cop% of emp2s value !utnot the ri+ht to alter it. he ar+ument n is initiali@ed tothe same value as emp2. he function then +oes on its merr% ,a%,ithout havin+ an% further interaction ,ith emp2. 8hat happensto n later doesnt matter; the value of n is thro,n a,a% as thefunction returns.

    his is calledpass by value. (he other principal method forpassin+ ar+umentsApass by referenceA re5uires pointers in 4 andis the su!$ect of 4hapter BCointers and Dther :harp=nstrumentsE.)Fs a conse5uence an% valid epression can !e passed as anar+ument as lon+ as it is the ri+ht t%pe. Gou arent limited topassin+ varia!les. he follo,in+ function calls are all le+al7temp ' 6actorial(1 * 2 * (- 9 1) );temp ' 6actorial(- * diff);result ' s5rt(1./ * 6actorial(thin+));6unctions can have multiple ar+uments. 6or eample here is aprotot%pe for the C%tha+oras function7dou!le C%tha+oras(dou!le a dou!le !);Fnd heres the function definition7dou!le C%tha+oras(dou!le a dou!le !) { return s5rt(a 3 a * ! 3 !);Dnce C%tha+oras is properl% declared and defined %ou can passan% t,o valid ar+uments. he first ar+ument in the function callis assi+ned to a; the second to !73 Cass -'>a H'>! 3

  • 7/27/2019 C Training Material

    25/179

    h%p1 ' C%tha+oras (-H);

    3 Cass H./'>a ./'>! 3h%p2 ' C%tha+oras (H./ ./);

    3 Cass temp1'>a *-'>!3h%p- ' C%tha+oras (temp1 *-);?ere of course the order doesnt matter. Iut it usuall% doesmatter ,ith most functions. 6or eample the Juadratic functiontreats its ar+uments differentl%7dou!le Juadratic(dou!le a dou!le ! dou!le c) { dou!le temp;

    temp ' s5rt(! 3 ! 9 H 3 a 3 c); return ((9! * temp) (2 3 a));

    )O%01 athematically0 this 'unction is incom"lete ecause it returns only one o' the t!o roots o' a)uadratic e)uation. -o!ever0 the 'unction can return only one value. n Cha"ter 0 youHll see ho! to returnmore than one value.

    Ffunction can even have no ar+uments. F trivial eample is afunction that prints a standard messa+e. he protot%pe uses thevoid 0e%,ord in the ar+ument list as does the functiondefinition. =n this contet void simpl% means Bno ar+uments.Eint Crint&messa+e(void);...int Crint&messa+e(void) { printf("6atal error7 stop the pro+ram."); return /;he function is then called ,ith an empt% ar+ument list !ut theparentheses must still !e used7temp ' Crint&messa+e();

    ' the 'unction has no need to return a value0 the return value may also e void. This means thatno value is returned at allL in that case0 no ret$rnexpressionstatement may a""ear !ithin the'unction de'inition0 and the 'unction0 !hen called0 cannot e used as "art o' a larger e4"ression.nstead0 a void'unction can e called only directly:

    Crint&messa+e();tHs not very common to see a 'unction !ith oth a voidreturn ty"e and a voidargument list0 utsuch a 'unction !ould e "er'ectly valid. Note the asence o' a ret$rnstatement in the 'unctionde'inition:void Crint&messa+e(void); 3 function protot%pe 3...void Crint&messa+e(void) { printf("6atal error7 stop the pro+ram.");

  • 7/27/2019 C Training Material

    26/179

    ' you have a "hiloso"hical turn o' mind0 you might thin o' voidas CHs contriution to theconce"t o' eing and nothingness. (To !hat entity does the !ord nothingre'erW* The voidey!ord can mean an em"ty argument list0 ormore "arado4icallya return value that is not areturn value0 ut is instead an indicator o' the absenceo' return value.

    %he o( of Rec$rsion

    Sim"ly stated0 recursionoccurs !hen a 'unction calls itsel'. This is legal in C0 as it is in manyother "rogramming languages.

    )O%01 8ecursion is an interesting logical and mathematical techni)ue0 ut itHs not vitalto the !riting o' most C "rograms. ' you are eager to understand 6ust the asics o' Csynta40 you can sa'ely si" this section.

    ou might thin that recursion leads automatically to an in'inite regress0 as is the case !hen you"oint a mirror at another mirror. #hen recursion is "ro"erly done0 this doesnHt ha""en at all0ecause there is an initial condition.,etHs return to the 'actorial e4am"le. The 'actorial o' a numer is the "roduct o' all the integers'rom = to the numer. or any numer n:factorial of n ' 1 3 2 3 - 3 ... n

    To go 'rom the 'actorial o' n ] = to n0 multi"ly y n. or e4am"le0 here are the 'actorials o' G and>:factorial of - ' 1 3 2 3 -factorial of H ' 1 3 2 3 - 3 H

    ulti"lying 'actorial o' G y > "roduces the 'actorial o' >. 2eneraliPing on this0 !e can say:factorial of n ' (factorial of n 9 1) 3 n

    There is one case in !hich this does not hold: the case o' the numer =. The 'actorial o' = is

    sim"ly =. So0 logically0 !e can say:' n = then 'actorial o' n [ ('actorial o' n =* \ nelse 'actorial o' n [ =#e can code this logic in a C 'unction very nicely y !riting a actorial 'unction that calls itsel':int actorial(int n* i' (n =* return (actorial(n =* \ n*L return =L

    M' n is greater than =0 the 'irst ret$rnstatement causes the 'unction to return immediately a'tercalculating the value. %nly i' n is not greater than = does the second ret$rnget e4ecuted. Thestatements there'ore create an Qi'thenelseR logic.This a""roach results in a !hole series o' 'unction calls0 ecause0 in most cases0 e'ore the'unction can com"lete e4ecution0 it must call itsel'. 1ut during each call to actorial0 there is adi''erent value o' n. This is "er'ectly 'ine. C su""orts multi"le instances o' the same 'unction0each !ith its o!n value o' n.' the main "rogram e4ecutes actorial(>*0 'or e4am"le0 the series o' actions is:

  • 7/27/2019 C Training Material

    27/179

    !Aain "rogram calls actorial(>*.Aactorial(>* calls actorial(G*.Aactorial(G* calls actorial(;*.EAactorial(;* calls actorial(=*.Aactorial(=* returns the value =.Aactorial(;* multi"lies this result y ; and returns ;.

    GAactorial(G* multi"lies this result y G and returns .HAactorial(>* multi"lies this result y > and returns ;>.

    8ecursion can e a use'ul techni)ue 'or e4"ressing a calculation succinctly. tHs most o'tena""licale in "rograms that involve com"le4 math or logical relationshi"s. 'owever. (o$ sho$lde aware that rec$rsion is almost never the most efficient wa( to imlement somethingA2enerally s"eaing0 any algorithm that can e e4"ressed through recursion also has an iterativesolutionthat is0 an a""roach that uses a loo" (such as a whileloo"*. The recursive a""roach isalmost al!ays less e''icient0 ecause 'or each 'unction call0 there is a certain amount o'overhead. $art o' the 'unction overhead stores the values o' arguments and local variales0 suchas n0 'or the "articular instance o' the 'unction call. The 'unction overhead also ee"s trac o'!here the 'unction returns !hen 'inished.

    #;m not sa(ing that (o$ sho$ld never $se rec$rsionI $t if there is an ovio$s alternativethat $ses a loo 3as is the case with factorials5. $se the loo instead . n some cases0 though0the recursive version may e much easier to !rite and nearly as e''icient.#hy do mention recursion0 i' it is rarely the est a""roachW 8ecursion is use'ul as a !ay o' illustrating a asic 'acto' most real!orld C "rograms: at any time0 there may e many 'unction calls "ending. %nly one 'unction call cane currently e4ecuting0 ut there may e a numer o' them !aiting 'or another 'unction to return.

    None o' that !ould e the case i' you did a!ay !ith all 'unctions e4ce"t main. n 'act0 you coulddo 6ust that0 using com"le4 loo"s and control structures to handle re"eated o"erations. -o!ever0such code !ould e e4ce"tionally di''icult to !rite0 understand0 and maintain0 even though intheory it might e slightly more e''icient. t !ouldnHt e reusaleL only !hen you !rite 'unctionscan you create "art o' a "rogram so that it can easily e reused in another "rogram.unctions0 a'ter all0 "rovide many ene'its. 5lthough machinelevel e''iciency is an im"ortant

    goal in C0 the aility o' a human eing to !rite good "rograms is even more im"ortant. or allthese reasons0 'unctions are an invaluale tool.

    ' you !ant to avoid having to !rite "rototy"es0 one !ay to do so is to de'ine a 'unctioncom"letely e'ore using it. This ottomu" a""roach means "utting main last.

    #ith this a""roach0 the actorial 'unction !ould e re!ritten as 'ollo!s:include Ustdio.h

    int actorial(int n* int result [ =L

    !hile (n =* /\ #hile n is greater than =0 \/ result \[ nL /\ multi"ly result y n and decrement n \/ return resultLM

    void main(* "rint'(IThe 'actorial o' G is ZdYnI0 actorial(G**L

  • 7/27/2019 C Training Material

    28/179

    "rint'(IThe 'actorial o' > is ZdYnI0 actorial(>**L "rint'(IThe 'actorial o' ? is ZdYnI0 actorial(?**LMost C "rogrammers donHt use this a""roach0 ecause they lie to start !ith the ig "icture (themain "rogram* and !or do!n!ard. oreover0 i' you s"end enough time "rogramming0 youHll

    'ind that ultimately there is no esca"e 'rom !riting "rototy"es. n a serious "rogram0 therelationshi"s et!een di''erent 'unctions ecome very com"le4. t is not uncommon 'or'unctions to end u" calling each other (a variation on recursion*0 in !hich case it is im"ossile tode'ine every 'unction e'ore it is called.The ottom line is that you might as !ell get into the hait o' "utting a "rototy"e 'or every'unction at the eginning o' your "rogram.

    > Final Word on Protot(es

    n many serious C "rograms0 you !onHt see "rototy"es at the eginning o' a sourcecode 'ile0 and'or a good reason: all the "rototy"es are "laced in a header 'ile0 !hich is then read in !ith a7incl$dedirective.

    This is a sensile a""roach0 es"ecially !hen you have multi"le source 'iles and !ant all o' themto get the "rototy"es 'or all the 'unctions in the "rogram. or e4am"le0 you might "lace"rototy"es 'or all your 'unctions in a 'ile called my9"rog.h. Then include my9"rog.h along !iththe other header 'iles:#include #include #include "m%&pro+.h"

    The synta4 'or the last 7incl$deis a little di''erent 'rom that o' the 'irst t!oL the )uotation marscause the current directory to e searched 'or the header 'ile.n the 'inal analysis0 entering "rototy"es may seem lie unnecessary !or at 'irst0 ut they are6ust too use'ul to ignoreas are 'unctions in general.

    OOP,

    OJect Oriented Programming

    Proced$ral. ,tr$ct$red. and OJect-Oriented Programming

    ntil recently0 "rograms !ere thought o' as a series o' "rocedures that acted u"on data. 5 "rocedure0 or'unction0 is a set o' s"eci'ic instructions e4ecuted one a'ter the other. The data !as )uite se"arate 'rom the"rocedures0 and the tric in "rogramming !as to ee" trac o' !hich 'unctions called !hich other'unctions0 and !hat data !as changed. To mae sense o' this "otentially con'using situation0 structured"rogramming !as created

    The "rinci"le idea ehind structured "rogramming is as sim"le as the idea o' divide and con)uer. 5com"uter "rogram can e thought o' as consisting o' a set o' tass. 5ny tas that is too com"le4 to edescried sim"ly !ould e roen do!n into a set o' smaller com"onent tass0 until the tass !eresu''iciently small and sel'contained enough that they !ere easily understood.5s an e4am"le0 com"uting the average salary o' every em"loyee o' a com"any is a rather com"le4 tas.ou can0 ho!ever0 rea it do!n into the 'ollo!ing sutass:

    !Aind out !hat each "erson earns.

    ACount ho! many "eo"le you have.

  • 7/27/2019 C Training Material

    29/179

    ATotal all the salaries.

    EADivide the total y the numer o' "eo"le you have.

    Totaling the salaries can e roen do!n into the 'ollo!ing ste"s:

    !A2et each em"loyeeHs record.

    A5ccess the salary.

    A5dd the salary to the running total.

    EA2et the ne4t em"loyeeHs record.

    n turn0 otaining each em"loyeeHs record can e roen do!n into the 'ollo!ing:

    !A%"en the 'ile o' em"loyees.

    A2o to the correct record.

    A8ead the data 'rom dis.

    Structured "rogramming remains an enormously success'ul a""roach 'or dealing !ith com"le4 "rolems.1y the late =B^Fs0 ho!ever0 some o' the de'iciencies o' structured "rogramming had ecome all too clear.

    5s "rograms gro! ever larger and more com"le40 even the structured "rogramming a""roachegins to sho! signs o' strain. ou may have heard aout0 or een involved in0 horror stories o' "rogramdevelo"ment. The "ro6ect is too com"le40 the schedule sli"s0 more "rogrammers are added0 com"le4ityincreases0 costs syrocet0 the schedule sli"s 'urther0 and disaster ensues.

    5nalyPing the reasons 'or these 'ailures reveals that there are !eanesses in the "rocedural "aradigm itsel'.No matter ho! !ell the structured "rogramming a""roach is im"lemented0 large "rograms ecomee4cessively com"le4.#hat are the reasons 'or these "rolems !ith "rocedural languagesW There are t!o related "rolems. irst0f$nctions have $nrestricted access to gloal dataASecond0 $nrelated f$nctions and data. the asis of

    the roced$ral aradigm. rovide a oor model of the real worldA

    #hen data items are modi'ied in a large "rogram it may not e easy to tell !hich 'unctions access the data0and even !hen you 'igure this out0 modi'ications to the 'unctions may cause them to !or incorrectly !ithother gloal data items. 3verything is related to everything else0 so a modi'ication any!here has 'arreaching0 and o'ten unintended0 conse)uences.

    The !ay !e are no! using com"uters!ith menus and uttons and !indo!s'osters a more interactive0eventdriven a""roach to com"uter "rogramming. 3ventdriven means that an event ha""ensthe user"resses a utton or chooses 'rom a menuand the "rogram must res"ond. $rograms are ecomingincreasingly interactive0 and it has ecame im"ortant to design 'or that ind o' 'unctionality.

    %ld'ashioned "rograms 'orced the user to "roceed ste"yste" through a series o' screens. odern eventdriven "rograms "resent all the choices at once and res"ond to the userHs actions. %6ectoriented"rogramming attem"ts to res"ond to these needs0 "roviding techni)ues 'or managing enormous com"le4ity0achieving reuse o' so't!are com"onents0 and cou"ling data !ith the tass that mani"ulate that data.The essence o' o6ectoriented "rogramming is to treat data and the "rocedures that act u"on the data as asingle Qo6ectRa sel'contained entity !ith an identity and certain characteristics o' its o!n.

    irst0 a natural desire is to thin o' data (em"loyee records0 'or e4am"le* and !hat you can do !ith data(sort0 edit0 and so on* as a single idea. $rocedural "rogramming !ored against this0 se"arating datastructures 'rom 'unctions that mani"ulated that data.

  • 7/27/2019 C Training Material

    30/179

    Second0programmers found themselves constantly reinventing new solutions to oldproblems. This is o'ten called Qreinventing the !heel0R !hich is the o""osite o'reusaility. The idea ehind reusaility is to uild com"onents that have no!n"ro"erties0 and then to e ale to "lug them into your "rogram as you need them. This ismodeled a'ter the hard!are !orld!hen an engineer needs a ne! transistor0 she doesnHt

    usually invent one0 she goes to the ig in o' transistors and 'inds one that !ors the !ayshe needs it to0 or "erha"s modi'ies it. No similar o"tion e4isted 'or a so't!are engineer.

    OJect

    The 'undamental idea ehind o6ectoriented languages is to comine into a single unitoth data and the 'unctions that o"erate on that data. Such a unit is called an o6ect.5n o6ectHs 'unctions0 called memer 'unctions in C++0 ty"ically "rovide the only !ay toaccess its data. ' you !ant to read a data item in an o6ect0 you call a memer 'unction inthe o6ect. t !ill access the data and return the value to you. ou canHt access the datadirectly. The data is hidden0 so it is sa'e 'rom accidental alteration.

    Class Class is the logical category /ty"e o' the %6ects. 5 class serves as a "lan0 or tem"late. t s"eci'ies !hatdata and !hat 'unctions !ill e included in o6ects o' that class. De'ining the class doesnHt create anyo6ects0 6ust as the mere e4istence o' data ty"e int doesnHt create any variales.

    0ncas$lation

    The "ro"erty o' eing a sel'contained unit is called enca"sulation. #ith enca"sulation0!e can accom"lish data hiding. Data hiding is the highly valued characteristic that ano6ect can e used !ithout the user no!ing or caring ho! it !ors internally.

  • 7/27/2019 C Training Material

    31/179

    to say0 Q,etHs uild another Star0 ut letHs add these additional ca"ailities. #eHll call thene! model a @uasar.R 5 @uasar is a ind o' Star0 ut a s"ecialiPed one !ith ne! 'eatures.C++ su""orts inheritance. 5 ne! ty"e0 !hich is an e4tension o' an e4isting ty"e0 can edeclared. This ne! suclass is said to derive 'rom the e4isting ty"e and is sometimescalled a derived ty"e. The @uasar is derived 'rom the Star and thus inherits all its

    )ualities0 ut can add to them as needed.nheritance allo!s you to create ne! o6ects o' a derived class 'rom "reviously de'inedo6ects o' a ase class. The derived class contains all the attriutes and methods o' thease class "lus any additional s"eci'ications o' the derived class. 5ny changes made toase classes are "ro"agated to all derived classes unless e4"licitly overridden.#nheritancefacilitates code re$se there( c$tting develoment costs

    >straction#hen the engineers at 5cme otors !ant to uild a ne! car0 they have t!o choices: They can start 'romscratch0 or they can modi'y an e4isting model/a set of modals. $erha"s a comination o' their Star modeland the Su"er Star model loos lie a great idea0 ut theyHd lie to add a turocharger and a si4s"eedtransmission. The chie' engineer !ould "re'er not to start 'rom the ground u"0 ut rather to say0 Q,etHsuild another model0 ut letHs add these additional ca"ailities. #eHll call the ne! model a Su"[email protected]

    5 Su"er@uasar is a ind o' Star com Su"er Star0 ut a s"ecialiPed one !ith ne! 'eatures.

    n the aove case the user/customer o' the ne! car Su"er@uassar never others to no! the technology (ie.The "arent technology 'rom !hich it is inherited in this case itHs a comination o' the star and su"er starmodel. *ehind it.This "rocess o' hiding the technology is called astraction.

    Wh( C++

    C++ 'ully su""orts o6ectoriented "rogramming0 including the three "illars o' o6ectorienteddevelo"ment: enca"sulation0 inheritance0 5straction and "olymor"hism

    > Comarison of C and C++

    #ntrod$ctionThe C "rogramming language !as develo"ed at 5T&T 'or the the "ur"ose o' !riting the o"erating system'or $D$== com"uters. This o"erating system evolved into ni4. 5s you can imagine C is a very e''icientlanguage since it !as designed to develo" an o"erating system. C++ is an e4tension o' C develo"ed y16arne Stroustro" (also o' 5T&T* !ith the "ur"ose o' adding o6ectoriented 'eatures to C !hile"reserving the e''iciencies o' C.

    ,imilarities

    The C language is a suset o' C++ 'or all "ractical "ur"oses even though it is "ossile to !rite C "rograms that arenot valid in C++. The main similarity in C and C++ lies in the synta4 o' the t!o languages. C and C++ oth sharemany o' the same 'undamental "rogramming constructs. This is the reason !hy it is easy 'or a "ro'icient C"rogrammer to learn C++ "rovided he/she understands the o6ectoriented "aradigm.

    C++ maintains it7s C roots at various levels:a* Source code level: most 5NS C "rograms are valid C++ "rogramsL* %6ect code level: C++ structures are Iinarycom"atileI !ith e)uivalent C structuresLc* 3nvironment/Tool level: C++ !ors !ith standard tools lie maeLC++ can e descried as a "rogramming language derived 'rom C !ith im"roved "rocedural synta4 ascom"ared to C and o6ectoriented 'eatures not "resent in C. Note that though C++ su""orts o6ectoriented"rogramming0 it does not en'orce it. C++ is there'ore a multi"aradigm language.

    Wh( is C++ etter than C 2

  • 7/27/2019 C Training Material

    32/179

    C is a "rocedural language. t is not designed to su""ort o6ectoriented "rogramming. n a "rocedural"rogram0 the "rolem is roen do!n into modules and sumodules !hich im"lement the solution. C++on the other hand can "rovide all the advantages inherent in the %% "aradigm. n an %% "rogram the"rolem s"ace is re"resented y o6ects that interact !ith each other and these o6ects are im"lementedalong !ith messaging mechanisms to "rovide a solution.%% "rogramming languages have a numer o' inherent advantages. They lend themselves to etter design

    ecause they allo! "rolem s"aces to e modelled lie real !orld o6ects. n an o6ect oriented language0an o6ect is called a class !hich is the so't!are re"resentation o' an o6ect. 5 class "acages all theattriutes and methods o' an o6ect. 5ttriutes are the data associated !ith the o6ect and methods are the'unctions that o"erate on the data and e4"ress the ehavior o' the o6ect. 5s an o6ectoriented language C++ su""orts inheritance0 enca"sulation and "olymor"hism !hich i' "ro"erly used lead to etter "rograms.-ere is a lin to the a rie' tutorial e4"laining the asics o' nheritance.

    nheritance in C++The 'ollo!ing is a lin to a tutorial on 3nca"sulation.Data -iding and 3nca"sulation in C++Chec out the 'ollo!ing lin 'or an introduction to "olymor"hism0 illustrated y e4am"le.5n ntroduction to $olymor"hism>n 0=amle

    Chec out this lin 'or a tutorial that e4"lores through e4am"les the di''erences et!een C and C++.Di''erences et!een C and C++>ftertho$ght

    Increasingly0 "eo"le seem to misinter"ret com"le4ity as so"histication0 !hich is a''ling theincom"rehensile should cause sus"icion0 rather than admirationI0 Nilaus #irth.

    Tryout lease

    ) *imple problem to *olve in +

    5cce"t t!o numers and dis"lay 5ll the even Numers et!een the t!o.

    5ll the odd Numers et!een the t!o.

    // the 'ile Nums.c""

    includeUiostream.h

    void main(*

    int inum=0inum;LcoutUUR3nter the irst Numer : QL//dis"lays the te4t in doule )uotes

    cininum=L//5cce"ts a eyoard in"ut 'rom the user to the varialecoutUUR 3nter the ;ndt Numer : QL//dis"lays the te4t in doule )uotescininum;L//5cce"ts a eyoard in"ut 'rom the user to the varialecoutUUR3ven Numers are : YnR'or(int [inum=LU[inum;L++*

    //n C++ variles can e declared as and !hen re)uired

    i' ((Z;* [[ F*

    coutUULM

    M

    coutUUR%dd Numers are : YnR'or(int [inum=LU[inum;L++*

    http://classes.monterey.edu/CST/CST338-01/world/Inheritance.htmlhttp://www.doc.mmu.ac.uk/STAFF/J.Gray/oopslang/aoblnts/c%2B%2Bnts/hiding.htmhttp://www.cs.bu.edu/teachingcpp/polymorphism/intro/slides/1.htmlhttp://www.icce.rug.nl/docs/cplusplus/cplusplus02.html%23l11http://classes.monterey.edu/CST/CST338-01/world/Inheritance.htmlhttp://www.doc.mmu.ac.uk/STAFF/J.Gray/oopslang/aoblnts/c%2B%2Bnts/hiding.htmhttp://www.cs.bu.edu/teachingcpp/polymorphism/intro/slides/1.htmlhttp://www.icce.rug.nl/docs/cplusplus/cplusplus02.html%23l11
  • 7/27/2019 C Training Material

    33/179

    i' ((Z;* J[ F*//The odulo 'unction returns a remainder

    coutUULM

    M

    M

    ,treams(/%*5s you have seen0 the statement

    cout UU Q3very age has a language o' its o!nYnRLcauses the "hrase in )uotation mars to e dis"layed on the screen. -o! does this !orW 5 com"lete descri"tion o'this statement re)uires an understanding o' o6ects0 o"erator overloading0 and other to"ics !e !onHt discuss untillater in the oo0 ut hereHs a rie' "revie!.The identi'ier cout ("ronounced QC outR* is actually an object.t is "rede'ined in C++ to corres"ond to thestandardoutput stream.5streamis an astraction that re'ers to a 'lo! o' data. The standard out"ut stream normally 'lo!s tothe screen dis"layalthough it can e redirected to other out"ut devices.

    The o"erator UU is called the insertionorput too"erator. t directs the contents o' the variale on its right to theo6ect on its le't(ie the co$t !hich is nothing ut the Standard %ut"ut Device*. n 8ST it directs the stringconstant Q3very age has a language o' its o!n YnR to cout0 !hich sends it to the dis"lay.

    Similarly the o"erator used !ith cin is a extraction or get opeator.t !aits 'or the in"ut o' the user 'rom the

    Standard n"ut Device (ie cin* and "uts it to the right hand side variale.

  • 7/27/2019 C Training Material

    34/179

    (' you no! C0 youHll recogniPe UU as the left-shiftit!ise o"erator and !onder ho! it can also e used to directout"ut. n C++0 o"erators can e overloaded (> wa( to imlement ol(morhism*. That is0 they can "er'orm

    di''erent activities0 de"ending on the conte4t.

    n the 8ST e4am"le0 the "re"rocessor directive include tells the com"iler to add the source 'ile %ST835 tothe 8ST.C$$ source 'ile e'ore com"iling. #hy do thisW %ST835 is an e4am"le o' a header file(sometimescalled an include file).tHs concerned !ith asic in"ut/out"ut o"erations0 and contains declarations that are neededy the cout identi'ier and the UU o"erator. #ithout these declarations0 the com"iler !onHt recogniPe cout and !illthin UU is eing used incorrectly. There are many such include 'iles. The ne!er Standard C++ header 'iles donHthave a 'ile e4tension0 ut some older header 'iles0 le't over 'rom the days o' the C language0 have the e4tension .-.' you !ant to see !hatHs in %ST8350 you can use your com"iler to 'ind the include directory 'or your com"ilerand dis"lay it as a source 'ile in the edit !indo!. %r you can loo at it !ith the #ord"ad or Note"ad utilities. Thecontents !onHt mae much sense at this "oint0 ut you !ill at least "rove to yoursel' that %ST835 is a source'ile0 !ritten in normal 5SC characters.

    0scae ,eK$encesThis second character constant0 _YtH0 is an odd one. ,ie _YnH !hich !e encountered earlier0 itHs an e4am"leo' an escape sequence.The name re'lects the 'act that the acslash causes an Qesca"eR 'rom the normal!ay characters are inter"reted. n this case the t is inter"reted not as the character _tH ut as the tacharacter. 5 ta causes "rinting to continue at the ne4t ta sto". n consolemode "rograms0 ta sto"s are"ositioned every eight s"aces. 5nother character constant0 _YnH0 is sent directly to cout in the last line o' the"rogram.3sca"e se)uences can e used oth as se"arate characters and also emedded in string constants. Taleelo! sho!s a list o' common esca"e se)uences.

    %ale Common 3sca"e Se)uences

    0scae ,eK$ence Character

    Ya 1ell (ee"*

    Y 1acs"ace

    Y' orm'eed

    Yn Ne!line

    Yr 8eturn

    Yt Ta

    YY 1acslash

    Y_ Single )uotation mar

    YQ Doule )uotation mars

    Y4dd -e4adecimal notation

  • 7/27/2019 C Training Material

    35/179

    Since the acslash0 the single )uotation mars0 and the doule )uotation mars all have s"ecialiPed meanings !henused in constants0 they must e re"resented y esca"e se)uences !hen !e !ant to dis"lay them as characters. -ereHsan e4am"le o' a )uoted "hrase in a string constant:cout UU QYR8un0 S"ot0 run0YR she said.RLThis translates toQ8un0 S"ot0 run0R she said.

    Sometimes you need to re"resent a character constant that doesnHt a""ear on the eyoard0 such as the gra"hicscharacters aove 5SC code =;. To do this0 you can use the _Y4ddH re"resentation0 !here each d stands 'or ahe4adecimal digit. ' you !ant to "rint a solid rectangle0 'or e4am"le0 youHll 'ind such a character listed as decimalnumer =^0 !hich is he4adecimal numer 1; in the 5SC tale. This character !ould e re"resented y thecharacter constant _Y41;H. #eHll see some e4am"les o' this later.

    Defining #nteger ?arialesnteger variales e4ist in several siPes0 ut the most commonly used is ty"e int. The amount o' memory occu"ied ythe integer ty"es is system de"endent. %n a G;it system lie #indo!s B^0 an int occu"ies > ytes (!hich is G;its* o' memory. This allo!s an int to hold numers in the range 'rom ];0=>0>^G0>^ to ;0=>0>^G0>. igure ;.Gsho!s an integer variale in memory.#hile ty"e int occu"ies > ytes on current #indo!s com"uters0 it occu"ied only ; ytes in SD%S and earlierversions o' #indo!s. The ranges occu"ied y the various ty"es are listed in the header 'ile ,TSL you can also

    loo them u" using your com"ilerHs hel" system.

    any com"ilers o''er integer ty"es that e4"licitly s"eci'y the numer o' its used. (8ememer there are ^ its to a

    yte.* These ty"e names are "receded y t!o underscores. They are 99int^0 99int=0 99intG;0 and 99int>. The99int^ ty"e corres"onds to char0 and (at least in G;it systems lie the current version o' #indo!s* The ty"e name99int= corres"onds to short and 99intG; corres"onds to oth int and long. The 99int> ty"e holds huge integers!ith u" to =B decimal digits. sing these ty"e names has the advantage that the numer o' ytes used 'or a varialeis not im"lementation de"endent. -o!ever0 this is not usually an issue0 and these ty"es are seldom used.

    What is a ointerW

    #hat is a "ointer W 5 "ointer is a variale that contains the memory address o' another variale(!hich maye o' any ty"e including an o6ect*. $ointers are central to C/C++ "rogramming asthey allo! the "rogrammer to access and mani"ulate o6ects in memory.

    %(es of ointers

    5 "ointer variale 6ust lie any other variale in C and C++ must have a data ty"e. The data ty"eo' a "ointer is the same as that o' the variale !hose address is contained in the "ointer. ore4am"le0 the 'ollo!ing are all valid declarations o' "ointers:

  • 7/27/2019 C Training Material

    36/179

    int \"tryntL //"trynt is a "ointer to an integer varialechar \"tryCharL //"tryChar is a "ointer to a char variale'loat \"tryloatL //"tryloat is a "ointer to a 'loat variale

    The \ in the variale name indicates that these variales are "ointers.

    #nitialiLing Pointers

    5 "ointer variale can e initialiPed in a numer o' di''erent !ays. 5 "ointer can e assigned theaddress o' a variale or it can e assigned another "ointer as illustrated in the e4am"les elo!://declare varialesint iLint \"tryntL

    //assign values to varialesi [ =FL//"trynt contains the address o' i"trynt [ &iL

    //declare and assign value to a second "ointerint \"trynt;L

    "trynt; [ "tryntL //"trynt; "oints to the address o' integer i

    %he #ndirection and the >ddress-of Oerators

    #e have 6ust seen the addresso' o"erator. This o"erator is used to access thememory address at !hich a variale is stored. or e4am"le i' !e have an integer i0then &i contains the memory location at !hich the integer i is stored.ndirection re'ers to the accessing o' the value stored in the memory addresscontained in the "ointer. or e4am"le0 i' !e de'ine a second integer 6 and !e !antto assign to 60 the value contained in the variale iL there are t!o !ays to do this:one !ithout "ointers and the second !ith "ointers. 1oth yield the same result.

    int iLi [ =FL

    int \"trL"tr [ &=FL

    int 6L6 [ iL //'irst !ay to assign a value to 66 [ \"trL //second !ay to assign a value to 6-ere7s another e4am"le continued 'rom the one !e 6ust looed at. Say !e de'ine avariale that uses the addresso' o"erator to "oint to the address o' i.

    int \L [ &iL

    Then i' !e assign a value to 0 !hat do you thin ha""ens to the value o' i W

    \ [ GL

    ou are right i' you guessed that the value o' i is no! e)ual to G. Since "oints to

  • 7/27/2019 C Training Material

    37/179

    the address0 assigning a value to \ actually changes the value stored in theaddress re'erenced y .

    What )e=t 2

    Chec out the 'ollo!ing lins 'or more on "ointers

    Notes on $ointers,ecture Notes on $ointers5 ntroduction to $ointers in C++$ointers and 8e'erences

    F$nctions

    5ny se)uence o' instructions that a""ears in a "rogram more than once is a candidate 'oreing made into a 'unction. The 'unctionHs code is stored in only one "lace in memory0even though the 'unction is e4ecuted many times in the course o' the "rogram. igureelo! sho!s ho! a 'unction is invoed 'rom di''erent sections o' a "rogram.

    ,imle F$nctions

    O$r first e=amle demonstrates a simle f$nction whose $rose is to rint a line of

    E asterissA %he e=amle rogram generates a tale. and lines of asteriss are $sed

    to mae the tale more readaleA 'ere;s the listing for %>B01// table.cpp// demonstrates simple function

    http://www.engineering.sdstate.edu/~hastingj/classes/csc250/notes/pointers.htmlhttp://cs1.ipfw.edu/cs331/Spring1999/lecture7/http://webstu.messiah.edu/~sm1181/misc/pointers.htmlhttp://www.cs.indiana.edu/~elyk/Classes/a304/Fall97/C%25252B%25252BExamples/pointers.htmlhttp://www.engineering.sdstate.edu/~hastingj/classes/csc250/notes/pointers.htmlhttp://cs1.ipfw.edu/cs331/Spring1999/lecture7/http://webstu.messiah.edu/~sm1181/misc/pointers.htmlhttp://www.cs.indiana.edu/~elyk/Classes/a304/Fall97/C%25252B%25252BExamples/pointers.html
  • 7/27/2019 C Training Material

    38/179

    #include using namespace std;

    void starline(); //functiondeclaration

    // (prototype)int main() { starline(); //call to function cout

  • 7/27/2019 C Training Material

    39/179

    other aroach is to defineit efore it;s calledI we;ll e=amine that ne=tA5A #n the

    %>B0 rogram. the f$nction starline35 is declared in the linevoid starline();

    %he declaration tells the comiler that at some later oint we lan to resent a

    f$nction called starline.%he e(word void secifies that the f$nction has no ret$rn

    val$e. and the emt( arentheses indicate that it taes no arg$mentsA 38o$ can also$se the e(word void in arentheses to indicate that the f$nction taes no

    arg$ments. as is often done in C. $t leaving them emt( is the more common

    ractice in C++A5 We;ll have more to sa( ao$t arg$ments and ret$rn val$es soonA

    )otice that the f$nction declaration is terminated with a semicolonA #t is a comlete

    statement in itselfA

    F$nction declarations are also calledprototypes,since the( rovide a model or

    l$erint for the f$nctionA %he( tell the comiler. 9a f$nction that loos lie this is

    coming $ later in the rogram. so it;s all right if (o$ see references to it efore (o$

    see the f$nction itselfA:

    Calling the F$nction

    %he f$nction is called3or invoked,or executed5 three times from main35A 0ach of the

    three calls loos lie this1starline();

    %his is all we need to call the f$nction1 the f$nction name. followed ( arentheses

    %he call is terminated ( a semicolonA 0=ec$ting the call statement ca$ses the

    f$nction to e=ec$teI that is. control is transferred to the f$nction. the statements in

    the f$nction definition 3which we;ll e=amine in a moment5 are e=ec$ted. and then

    control ret$rns to the statement following the f$nction callA

    %he F$nction Definition

    Finall(. we come to the f$nction itself. which is referred to as the f$nction definition.

    %he definition contains the act$al code for the f$nctionA 'ere;s the definition for

    starline351void starline() //declarator { for(int 0-;

  • 7/27/2019 C Training Material

    40/179

    When the f$nction is called. control is transferred to the first statement in the

    f$nction od(A %he other statements in the f$nction od( are then e=ec$ted. and

    when the closing race is enco$ntered. control ret$rns to the calling rogramA

    Comarison with irar( F$nctions

    We;ve alread( seen some lirar( f$nctions in $seA We have emedded calls to

    lirar( f$nctions. s$ch asc" 0 getc"e();

    in o$r rogram codeA Where are the declaration and definition for this lirar(

    f$nction2 %he declaration is in the header file secified at the eginning of the

    rogram 3CO)#OA'. for getche355A %he definition 3comiled into e=ec$tale code5 is

    in a lirar( file that;s lined a$tomaticall( to (o$r rogram when (o$ $ild itA

    When we $se a lirar( f$nction we don;t need to write the declaration or definitionA

    B$t when we write o$r own f$nctions. the declaration and definition are art of o$r

    so$rce file.

    0liminating the Declaration

    %he second aroach to inserting a f$nction into a rogram is to eliminate the

    f$nction declaration and lace the f$nction definition 3the f$nction itself5 in the

    listing efore the first call to the f$nctionA For e=amle. we co$ld rewrite %>B0 to

    rod$ce %>B0. in which the definition for starline35 aears firstA

    // taleAc

    // demonstrates f$nction definition receding f$nction calls

    7incl$de iostreamN

    $sing namesace stdI //no f$nction declaration

    //--------------------------------------------------------------// starline35 //f$nction definition

    void starline35

    for3int J"I JEI J++5

    co$t Q;I

    co$t endlI

    S

    //--------------------------------------------------------------

    int main35 //main35 follows f$nction

    starline35I //call to f$nction co$t 9Data t(e Range: endlI

    starline35I //call to f$nction

    co$t 9char -!H to !G: endl

    9short -.GH to .GG: endl

    9int ,(stem deendent: endl

    9long -.!EG.EH.EH to .!EG.EH.EG: endlI

    starline35I //call to f$nction

    ret$rn "I

  • 7/27/2019 C Training Material

    41/179

    S

    %his aroach is simler for short rograms. in that it removes the declaration. $t it is

    less fle=ileA %o $se this techniK$e when there are more than a few f$nctions. the

    rogrammer m$st give considerale tho$ght to arranging the f$nctions so that each one

    aears efore it is called ( an( otherA ,ometimes this is imossileA >lso. man(

    rogrammers refer to lace main35 first in the listing. since it is where e=ec$tion eginsAPassing >rg$ments to F$nctions

    >n argumentis a iece of data 3an int val$e. for e=amle5 assed from a rogram to

    the f$nctionA >rg$ments allow a f$nction to oerate with different val$es. or even to

    do different things. deending on the reK$irements of the rogram calling itA

    >s an e=amle. let;s s$ose we decide that the starline35 f$nction in the last

    e=amle is too rigidA #nstead of a f$nction that alwa(s rints E asteriss. we want a

    f$nction that will rint an( character an( n$mer of timesA

    'ere;s a rogram. %>B0>R6. that incororates J$st s$ch a f$nctionA We $se

    arg$ments to ass the character to e rinted and the n$mer of times to rint itA

    // tablearg.cpp// demonstrates function arguments#include using namespace std;void repc"ar(c"ar int); //functiondeclaration

    int main() { repc"ar(35 ,); //call to function

    cout

  • 7/27/2019 C Training Material

    42/179

    %he new f$nction is called rechar35A #ts declaration loos lie this1void repc"ar(c"ar int); // declaration specifies datatypes

    %he items in the arentheses are the data t(es of the arg$ments that will e sent to

    rechar351 char and intA

    #n a f$nction call. secific val$esTconstants in this caseTare inserted in thearoriate lace in the arentheses1repc"ar(35 ,); // function call specifies actual values

    %his statement instr$cts rechar35 to rint a line of E dashesA %he val$es s$lied

    in the call m$st e of the t(es secified in the declaration1 the first