View
221
Download
0
Category
Preview:
Citation preview
CforPythonProgrammers
BBM101- Introduction toProgramming I
Hacettepe UniversityFall2015
FuatAkal,AykutErdem,Erkut Erdem,Vahid Garousi
1Slides basedonthematerialpreparedbyCarlBurch(HendrixCollege)withmodifications byElizabethPatitsas (UToronto)
Creatingcomputerprograms
• Eachprogramminglanguageprovidesasetofprimitiveoperations
• Eachprogramminglanguageprovidesmechanismsforcombiningprimitivestoformmorecomplex,butlegal,expressions
• Eachprogramminglanguageprovidesmechanismsfordeducingmeaningsorvaluesassociatedwithcomputationsorexpressions
Slidecredit:E.Grimson, J.Guttag andC.Terman
Recallourgoal
• Learnthesyntaxandsemanticsofaprogramminglanguage
• Learnhowtousethoseelementstotranslate“recipes”forsolvingaproblemintoaform thatthecomputercanusetodo theworkforus
• Computationalmodesofthoughtenableustouseasuiteofmethodstosolveproblems
Slidecredit:E.Grimson, J.Guttag andC.Terman
Today
• OverviewofProgramminglanguages(PLs)– DimensionsofaPL– Programmingparadigms
• HowPython&Caresimilar• HowPython&Caredifferent– Cfundamentals– CExamples
4
Today
• OverviewofProgramminglanguages(PLs)– DimensionsofaPL– Programmingparadigms
• HowPython&Caresimilar• HowPython&Caredifferent– Cfundamentals– CExamples
5
DimensionsofaProgrammingLanguage• Low-levelvs.High-level– Distinctionaccordingtothelevelofabstraction– Inlow-levelprogramminglanguages(e.g.Assembly),thesetofinstructionsusedincomputationsareverysimple(nearlyatmachinelevel)
– Ahigh-levelprogramminglanguage(e.g.C,Java)hasamuchricherandmorecomplexsetofprimitives.
DimensionsofaProgrammingLanguage• Generalvs.Targeted– Distinctionaccordingtotherangeofapplications– Inageneralprogramminglanguage,thesetofprimitivessupportabroadrangeofapplications.
– Atargetedprogramminglanguage aimsataveryspecificsetofapplications.• e.g.,MATLAB(matrixlaboratory)isaprogramminglanguagespecificallydesignedfornumericalcomputing(matrixandvectoroperations)
DimensionsofaProgrammingLanguage• Interpretedvs.Compiled– Distinctionaccordingtohowthesourcecodeisexecuted– Ininterpretedlanguages(e.g.Python),thesourcecodeisexecuteddirectlyatruntime(bytheinterpreter).• Interpretercontrolthetheflowoftheprogrambygoingthrougheachoneoftheinstructions.
– Incompiledlanguages(e.g.C),thesourcecodefirstneedstobetranslatedtoanobjectcode(bythecompiler)beforetheexecution.
– Morelatertoday!
ProgrammingLanguageParadigms• Functional
• Treatscomputationastheevaluationofmathematicalfunctions(e.g.Lisp,Scheme,Haskell,etc.)
• Imperative• describescomputationintermsofstatementsthatchangeaprogramstate(e.g.FORTRAN,BASIC,Pascal,C,etc.)
• Logical(declarative)• expressesthelogicofacomputationwithoutdescribingitscontrolflow(e.g.Prolog)
• Objectoriented• uses"objects"– datastructuresconsistingofdatafieldsandmethodstogetherwiththeirinteractions– todesignapplicationsandcomputerprograms(e.g.C++,Java,C#,Python,etc.)
C(1973)
• DevelopedbyKenThompsonandDennisRitchieatAT&TBellLabsforuseontheUNIXoperatingsystem.– nowusedonpracticallyeveryoperatingsystem– popularlanguageforwritingsystemsoftware
• Features:– Anextremelysimplecorelanguage,withnon-essential
functionalityprovidedbyastandardizedsetoflibraryroutines.– Low-levelaccesstocomputermemoryviatheuseofpointers.
• Cancestors:C++,C#,Java
10Slidecredit:ThomasJ.Cortina
TheStrangeBirthandLongLifeofUnix
• http://spectrum.ieee.org/computing/software/the-strange-birth-and-long-life-of-unix
Photo:Alcatel-Lucent
Python
• CreatedbyGuidovanRossum inthelate1980s• Allowsprogramminginmultipleparadigms:object-oriented,structured,functional
• Usesdynamictypingandgarbagecollection
Slidecredit:ThomasJ.Cortina
Today
• OverviewofProgramminglanguages(PLs)– DimensionsofaPL– Programmingparadigms
• HowPython&Caresimilar• HowPython&Caredifferent– Cfundamentals– CExamples
13
BuildingasimpleprograminC(ascomparedtoPython)
• Compilersversusinterpreters• Variabledeclarations• Whitespace• The printf() function• Functions
14
Compilersversusinterpreters
• OnemajordifferencebetweenCandPythonishowtheprogramswritteninthesetwolanguages areexecuted.
• WithCprograms,youusuallyusea compiler whenyouarereadytoseeaCprogramexecute.
• Bycontrast,withPython,youtypicallyusean interpreter.
15
Compilersversusinterpreters
• An interpreter readstheuser-writtenprogramandperformsitdirectly.
• A compiler generatesafilecontainingthetranslationoftheprogramintothemachine'snativecode.– Thecompilerdoesnotactuallyexecutetheprogram!– Instead,youfirstexecutethecompilertocreateanativeexecutable,andthenyouexecutethegeneratedexecutable.
16
TheProgrammingProcessinC
• AftercreatingaCprogram,executingitisatwostepprocess:
me@computer:~$ gcc my_program.cme@computer:~$ ./a.out
17
TheProgrammingProcessinC
me@computer:~$ gcc my_program.cme@computer:~$ ./a.out
• invokesthecompiler,named gcc.• Thecompilerreadsthesourcefile my_program.ccontainingtheCcodes
• Itgeneratesanewfilenamed a.out containingatranslationofthiscodeintothebinarycodeusedbythemachine.
18
Compilersversusinterpreters
me@computer:~$ gcc my_program.cme@computer:~$ ./a.out
• tellsthecomputertoexecutethisbinarycode.• Asitisexecutingtheprogram,thecomputerhasnoideathat a.outwasjustcreatedfromsomeCprogram.
19
TheProgrammingProcessinC
Create/EditProgram Compile Execute
“Thecycleendsoncetheprogrammerissatisfiedwiththeprogram,e.g.,performanceandcorrectness-wise.”
Compilersversusinterpreters
• An interpreter readstheuser-writtenprogramandperformsitdirectly.
• A compiler generatesafilecontainingthetranslationoftheprogramintothemachine'snativecode.
• Beingcompiledhassomeradicalimplicationstolanguagedesign.
• CisdesignedsothecompilercantelleverythingitneedstoknowtotranslatetheCprogramwithoutactuallyexecutingtheprogram.
21
Variabledeclarations
• Crequires variabledeclarations, informingthecompileraboutthevariablebeforethevariableisactuallyused.
• InC,thevariabledeclarationdefinesthevariable's type.• NosuchthinginPython!
22
DeclaringaVariable
• Declaringavariableissimpleenough.• Youenterthevariable'stype,somewhitespace,
thevariable'sname,andasemicolon:
double x;
• ValueassignmentissimilartoPython:
x=3;• x willactuallyholdthefloating-pointvalue3.0ratherthanthe
integer3.• However,onceyoudeclareavariabletobeofaparticular
type,youcannotchangeitstype!
23
DeclaringaVariable
• InC,variabledeclarationsbelongatthetopofthefunctioninwhichtheyareused.
• Ifyouforgettodeclareavariable,thecompilerwillrefusetocompiletheprogram:– A variableisusedbutisnotdeclared.
• ToaPythonprogrammer,itseemsapaintohavetoincludethesevariabledeclarationsinaprogram,thoughthisgetseasierwithmorepractice.
24
Whitespace
• InPython,whitespacecharactersliketabsandnewlinesareimportant:– Youseparateyourstatementsbyplacingthemonseparatelines,andyouindicatetheextentofablockusingindentation.
– likethebodyofa while or ifstatement
• Cdoesnotusewhitespaceexceptforseparatingwords.• Moststatementsareterminatedwithasemicolon';',and
blocksofstatementsareindicatedusingasetofbraces,'{'and'}'.
25
WhitespaceCfragmentdisc = b * b - 4 * a * c;if (disc < 0){
num_sol = 0;}else{
t0 = -b / a;if (disc == 0){
num_sol = 1;sol0 = t0 / 2;
}else{
num_sol = 2;t1 = sqrt(disc) / a;sol0 = (t0 + t1) / 2;sol1 = (t0 - t1) / 2;
}}
Pythonequivalentdisc = b * b - 4 * a * cif disc < 0:
num_sol = 0else:
t0 = -b / aif disc == 0:
num_sol = 1sol0 = t0 / 2
else:num_sol = 2t1 = disc ** 0.5 / asol0 = (t0 + t1) / 2sol1 = (t0 - t1) / 2
26
Whitespace• Assaid,whitespaceisinsignificantinC.• Thecomputerwouldbejustashappyifthepreviouscode
fragmentiswrittenasfollows:
disc=b*b-4*a*c;if(disc<0){num_sol=0;}else{t0=-b/a;if(disc==0){num_sol=1;sol0=t0/2;}else{num_sol=2;t1=sqrt(disc/a;sol0=(t0+t1)/2;sol1=(t0-t1)/2;}}
• However,donotwriteyourprogramslikethis!
27
Theprintf()function
• InPython,displayingresultsfortheuserisaccomplishedbyusing print.
• InC,insteadyouusethe printf()functionwhichisprovidedbytheC'sstandardlibrary.
• Thewaytheparametersto printf()work isabitcomplicatedbutalsoquiteconvenient.
28
Theprintf()function
• Thefirstparameterisastringspecifyingtheformatofwhattoprint,andthefollowingparametersindicatethevaluestoprint.
• Considerthefollowingexample:printf("# solns: %d\n", num_sol);
• “# solns: %d\n” istheformatstring,num_sol isthevaluetobeprinted.
• Thepercentcharacterisspecialto printf().– Itsaystoprintavaluespecifiedinasubsequentparameter.– %d forintegers/decimals
• Ifthevaluestoredinnum_sol is2,theoutputis:# solns: 2
29
Theprintf()function
• LikePython,Callowsyoutoincludeescapecharactersinastringusingabackslash:– The“\n”sequencerepresentsthenewlinecharacter,– The“\t”sequencerepresentsthetabcharacter,– “\"”sequence representsthedouble-quotecharacter,– “\\”sequencerepresentsthebackslashcharacter.
• TheseescapecharactersarepartofCsyntax,notpartoftheprintf() function.
30
Theprintf()function
• Let'slookatanotherexample.printf("# of solns: %d\n", num_sol);printf("solns: %f, %f", sol0, sol1);
• Let'sassumenum_sol holds2, sol0 holds4,andsol1 holds1.
• Whenthecomputerreachesthesetwoprintf() functioncalls,itexecutesthemsequentially.
• Theoutputis:# of solns: 2
solns: 4.0, 1.0
31
Theprintf()function
• There'savarietyofcharactersthatcanfollowthepercentcharacterintheformattingstring.– %d,aswe'vealreadyseen,saystoprintan int valueindecimal
form.– %f saystoprinta double valueindecimal-pointform.– %e saystoprinta double valueinscientificnotation(for
example,3.000000e8).– %c saystoprinta char value.– %s saystoprintastring.
• There'snovariabletypeforrepresentingastring,butCdoessupportsomestringfacilitiesusingarraysofcharacters.
32
Functions• UnlikePython,allCcodemustbenestedwithinfunctions,
andfunctionscannotbenestedwithineachother.• ACprogram'soverallstructureistypicallyvery
straightforward.• Itisalistoffunctiondefinitions,oneafteranother,each
containingalistofstatementstobeexecutedwhenthefunctioniscalled.
33
Functions• ACfunctionisdefinedbynamingthereturntype,followedbythefunction
name,followedbyasetofparentheseslistingtheparameters.• Eachparameterisdescribedbyincludingthetypeoftheparameterandthe
parametername.• Here's asimpleexample of afunction definition:
float expon(float b, int e){
if (e == 0){
return 1.0;}else{
return b * expon(b, e - 1);}
}
34
Thisis afunction namedexpon,which takes twoarguments, first afloating pointnumber and next aninteger,and returns afloating pointnumber.
Functions
• Ifyouhaveafunctionthatdoesnothaveanyusefulreturnvalue,thenyou'duse void asthereturntype.
• Programshaveonespecialfunctionnamed main,whosereturntypeisaninteger.
• Thisfunctionisthe“startingpoint”fortheprogram:– Thecomputeressentiallycallstheprogram's main functionwhenitwantstoexecutetheprogram.
– Theintegerreturnvalueislargelymeaningless;we'llalwaysreturn0ratherthanworryingabouthowthereturnvaluemightbeused.
35
FunctionsCprogramint gcd(int a, int b){if (b == 0){
return a;}else{
return gcd(b, a % b);}
}
int main(){printf("GCD: %d\n“, gcd(24,40));return 0;
}
Pythonprogramdef gcd(a, b):if b == 0:
return aelse:
return gcd(b, a % b)
print("GCD: " + str(gcd(24, 40)))
36
OperatorsinCMajoroperatorsinCandPython
• Theylooksimilarbuttherearesomesignificantdifferences 38
Coperatorprecedence Pythonoperatorprecedence++ -- (postfix) **+ - ! (unary) + - (unary)* / % * / % //+ - (binary) + - (binary)< > <= >= < > <= >= == !=== != not&& and|| or= += -= *= /= %=
OperatorsinC–ImportantDistinctions
39
• CdoesnothaveanexponentiationoperatorlikePython's**operator.ForexponentiationinC,you'dwanttousethelibraryfunctionpow().Forexample,pow(1.1, 2.0) computes1.1².
• CusessymbolsratherthanwordsfortheBooleanoperationsAND(&&),OR(||),andNOT(!).
• TheprecedencelevelofNOT(the! operator)isveryhighinC.Thisisalmostneverdesired,soyouendupneedingparenthesesmosttimesyouwanttousethe! operator.
OperatorsinC–ImportantDistinctions
• Cdefinesassignmentasanoperator,whereasPythondefinesassignmentasastatement.
• Thevalueoftheassignmentoperatoristhevalueassigned.• AconsequenceofC'sdesignisthatanassignmentcan
legallybepartofanotherstatement.• Example:
– Thevaluereturnedbygetchar() isassignedtothevariablea,– Thevalueassignedtoa istestedwhetheritmatchestheEOF
constant– Itisusedtodecidewhethertorepeattheloopagain.
40
while ((a = getchar()) != EOF)
OperatorsinC–ImportantDistinctions
• Cdefinesassignmentasanoperator,whereasPythondefinesassignmentasastatement.
• Thevalueoftheassignmentoperatoristhevalueassigned.• AconsequenceofC'sdesignisthatanassignmentcan
legallybepartofanotherstatement.• Example:
– Thevaluereturnedbygetchar() isassignedtothevariablea,– Thevalueassignedtoa istestedwhetheritmatchestheEOF
constant– Itisusedtodecidewhethertorepeattheloopagain.
41
while ((a = getchar()) != EOF)
OperatorsinC–ImportantDistinctions
• C'soperators++ and-- areforincrementinganddecrementingavariable.Thus,thestatement“i++”isashorterformofthestatement“i = i + 1”(or“i += 1”).”
• C'sdivisionoperator/ doesintegerdivisionifbothsidesoftheoperatorhaveanint type;thatis,anyremainderisignoredwithsuchadivision.– Thus,inCtheexpression“13/5”evaluatesto2,while“13/5.0” is2.6:Thefirsthasintegervaluesoneachside,whilethesecondhasafloating-pointnumberontheright.
42
BasictypesinC
• C'slistofbasictypesisquiteconstrained.int foranintegerchar forasinglecharacterfloat forasingle-precisionfloating-pointnumberdouble foradouble-precisionfloating-pointnumber
• DataTypeModifiers– signed /unsigned– short /long
43
int
• 4bytes(onUnix)• Base-2representation.• needonebitfor+or-• Range:-231 to231
• Variants:short (2bytes),long (8bytes),unsigned(onlynon-negative)
Slidecredit:BertHuang
float
• Standsfor“floatingdecimalpoint”• 4bytes• Similartoscientificnotation:4.288*103
• Verydifferentinterpretationofbitsthanint andchar.• Range:-1038 to1038
Slidecredit:BertHuang
NoBooleantypeforrepresentingtrue/false
• Thishasmajorimplicationsforastatementlikeif,whereyouneedatesttodeterminewhethertoexecutethebody.C'sapproachistotreattheinteger0asfalse andallotherintegervaluesastrue.
• Example
47
int main() {int i = 5;if (i) {
printf("in if\n");} else {
printf("in else\n");}return 0;
}
prints“in if”whenexecutedsincethevalueof(i) is5whichisnot0
NoBooleantypeinC!
• C'soperatorsthatlookliketheyshouldcomputeBooleanvalues(like ==,&&,and||)actuallycomputeint valuesinstead.
• Inparticular,theycompute1torepresenttrue and0torepresentfalse.
• Thismeansthatyoucouldlegitimatelytypethefollowingtocounthowmanyofa,b,andcarepositive.
48
pos = (a > 0) + (b > 0) + (c > 0);
NoBooleantypeinC!
• C'soperatorsthatlookliketheyshouldcomputeBooleanvalues(like ==,&&,and||)actuallycomputeint valuesinstead.
• Inparticular,theycompute1torepresenttrue and0torepresentfalse.
• Thismeansthatyoucouldlegitimatelytypethefollowingtocounthowmanyofa,b,andcarepositive.
49
pos = (a > 0) + (b > 0) + (c > 0);
BasicDataTypesType SizeinBytes Rangesigned char 1 -127to+127unsigned char 1 0to255short int 2 -32,767to+32,767unsigned short int 2 0to65535int 4 -32,767to+32,767unsigned int 4 0to65,535long int 8 -2,147,483,647to+2,147,483,647unsigned long int 8 0to4,294,967,295float 4 ~10-37 to~1038
double 8 ~10-307 to~10308
long double 16 ~10-4931 to~104932
Braces
• Severalstatements,liketheif statement,includeabodythatcanholdmultiplestatements.
• Typicallythebodyissurroundedbybraces('{'and'}')toindicateitsextent.Butwhenthebodyholdsonlyasinglestatement,thebracesareoptional.
• Example:
51
if (first > second)max = first;
elsemax = second;
Braces
• Cprogrammersusethisquiteoftenwhentheywantoneofseveralif teststobeexecuted.
• Example:
52
disc = b * b - 4 * a * c;if (disc < 0) {
num_sol = 0;}else {
if (disc == 0) {num_sol = 1;
} else {
num_sol = 2;}
}
Noticethattheelse clausehereholdsjustonestatement(anif…elsestatement),sowecanomitthebracesaroundit.
Braces
• Cprogrammersusethisquiteoftenwhentheywantoneofseveralif teststobeexecuted.
• Example:
53
disc = b * b - 4 * a * c;if (disc < 0) {
num_sol = 0;}else
if (disc == 0) {num_sol = 1;
} else {
num_sol = 2;}
ButthissituationarisesoftenenoughthatCprogrammersfollowaspecialruleforindentinginthiscase— arulethatallowsallcasestobewrittenatthesamelevelofindentation.
Braces
• Cprogrammersusethisquiteoftenwhentheywantoneofseveralif teststobeexecuted.
• Example:
54
disc = b * b - 4 * a * c;if (disc < 0) {
num_sol = 0;}else if (disc == 0) {
num_sol = 1;} else {
num_sol = 2;}
Braces
• Cprogrammersusethisquiteoftenwhentheywantoneofseveralif teststobeexecuted.
• Example:
55
disc = b * b - 4 * a * c;if (disc < 0) {
num_sol = 0;}else if (disc == 0) {
num_sol = 1;} else {
num_sol = 2;}
Statements
2. AnexpressionasastatementTwoforms:– Anoperatorthatchangesavariable'svalue,liketheassignmentoperator(“x = 3;”),theadditionassignmentoperator+=,orthetheincrementoperator++.• Example:
– Afunctioncall,likeastatementthatsimplycallstheprintf() function.• Example:
57
x = y + z;
printf("%d", x);
Statements3. An if statement–WorksverysimilarlytoPython'sif statement– Theonlymajordifferenceisthesyntax:• InC,anif statement'sconditionmustbeenclosedinparentheses,thereisnocolonfollowingthecondition,andthebodyhasasetofbracesenclosingit.• Aswe'vealreadyseen,Cdoesnothaveanelif clauseasinPython;instead,Cprogrammersusetheoptional-braceruleandwrite“else if”.
– Example:58if (x < 0) { printf("negative"); }
Statements
4. Areturn statement– Youcanhaveareturn statementtoexitafunctionwithagivenreturnvalue.
– Orforafunctionwithnoreturnvalue(andavoidreturntype),youwouldwritesimply“return;”.
– Example:
59
return 0;
Statements
5. Awhile statement– Thewhile statementworksidenticallytoPython's,althoughthesyntaxisdifferentinthesamewaythattheif syntaxisdifferent.
– Example:
60
while (i >= 0) {
printf("%d\n", i);i--;
}
Statements
6. Aforstatement– WhilePythonalsohasafor statement,itspurposeanditssyntaxbearscantsimilaritytoC'sforstatement
– Syntax:for (init; test; update)
body;
• Theprogramwillkeepexecutingthebodyinsidethefor aslongastheconditionistrue(nonzero)
• Theinit istestedbeforeeachiterationoftheloop.Theloopterminateswhentheconditionisfalse.
• Theloopiscontrolledbyavariablewhichisinitializedandmodifiedbytheinit andupdate(e.g.incrementoperation)expressions,respectively. 61
Statements
6. Aforstatement(cont’d.)– Example1:
– Example2:
62
for (p = 1; p <= 512; p *= 2){
printf("%d\n", p);}
for (i = 0; i < n; i++) {body
}
for loopsaremostlyusedforcountingoutniterations
Noticehowtheupdateportionoftheforstatementhaschangedto“p *= 2”.
Arrays
• Pythonsupportsmanytypesthatcombinethebasicatomictypesintoagroup:tuples,lists,strings,dictionaries,sets.
• C'ssupportismuchmorerudimentary:Theonly compositetypeisthearray– SimilartoPython'slistexceptthatanarrayinCcannotgrowor
shrink— itssizeisfixedatthetimeofcreation.• Example:
• Anotherwaytomakeanarray,ifyouknowalltheelementsupfront,is:
63
double pops[50];pops[0] = 897934;pops[1] = pops[0] + 11804445;
char vowels[6]={'a','e','i','o','u','y'};
Arrays• Cdoesnothaveansupportforaccessingthelengthofanarrayonceitiscreated;thatis,thereisnothinganalogoustoPython'slen(pops)
• Whathappensifyouaccessanarrayindexoutsidethearray,likeaccessingpops[50]orpops[-100]?– WithPython,thiswillterminatetheprogramwithafriendlymessagepointingtothelineatfaultandsayingthattheprogramwentbeyondthearraybounds.
– Cisnotnearlysofriendly.Whenyouaccessbeyondanarraybounds,itblindlydoesit.
64
Arrays• Example:
• Somesystems(includingsomeLinuxdistributions)wouldplaceiinmemoryjustafterthevals array.
• Wheni reaches5andthecomputerexecutes“vals[i] = 0”,itinfactresetsthememorycorrespondingtoi to0.– Thefor loophasreset,andtheprogramgoesthroughtheloopagain,and
again,repeatedly.– Theprogramneverreachestheprintf functioncall,andtheprogramnever
terminates.65
int main() {int i;int vals[5];
for (i = 0; i <= 5; i++) {vals[i] = 0;
}printf("%d\n", i);return 0;
}
Arrays• Example:
• Somesystems(includingsomeLinuxdistributions)wouldplaceiinmemoryjustafterthevals array.
• Wheni reaches5andthecomputerexecutes“vals[i] = 0”,itinfactresetsthememorycorrespondingtoi to0.– Thefor loophasreset,andtheprogramgoesthroughtheloopagain,and
again,repeatedly.– Theprogramneverreachestheprintf functioncall,andtheprogramnever
terminates.66
int main() {int i;int vals[5];
for (i = 0; i <= 5; i++) {vals[i] = 0;
}printf("%d\n", i);return 0;
}
Comments
• InC'soriginaldesign,allcommentsbeginwithaslashfollowedbyanasterisk(“/*”)andendwithanasteriskfollowedbyaslash(“*/”).
• Thecommentcanspanmultiplelines.• Example:
67
/* gcd - returns the greatest common* divisor of its two parameters */int gcd(int a, int b) {
...
Comments
• C++introducedasingle-linecommentthathasprovensohandythatmostoftoday'sCcompilersalsosupportit.
• Itstartswithtwoslashcharacters(“//”)andgoestotheendoftheline.
• Example:
68
int gcd(int a, int b) {if (b == 0) {return a;
}else {// recurse if b != 0return gcd(b, a % b);
}}
Functionprototypes
• InC,afunctionmustbedeclaredabovethelocationwhereyouuseit.
• Thecompilerwouldcomplainifafunctioniscalledbeforedefiningit.
• ThereasonisCassumesthatacompilerreadsaprogramfromthetoptobottom.
• Onewaytogetaroundthis,istousefunctionprototyping,writingthefunctionheaderbutomittingthebodydefinition.
70
Functionprototypes• Considerthefollowingexample:
int gcd(int a, int b);
int main(){
printf("GCD: %d\n", gcd(24, 40));return 0;
}
• Byusing function prototypes,we aredeclaring that the function willeventually be defined,butwe arenotdefining it yet.
• The compiler accepts this andobediently compiles the programwith nocomplaints.
71
Linefor the function prototype
Headerfiles
• Largerprogramsspanningseveralfilesfrequentlycontainmanyfunctionsthatareusedmanytimesinmanydifferentfiles.
• Itwouldbepainfultorepeateveryfunctionprototypeineveryfilethathappenstousethefunction.
• Soweinsteadcreateafilecalleda headerfile.
72
Headerfiles
• Aheaderfilecontainseachprototypewrittenjustonce(andpossiblysomeadditionalsharedinformation).
• Theheaderfilescanthenbereferredtoineachsourcefilethatwantstheprototypes.
• Thefileofprototypesiscalledaheaderfile,sinceitcontainsthe“heads”ofseveralfunctions.
• Conventionally,headerfilesusethe .h prefix,ratherthanthe .c prefixusedforCsourcefiles.
73
Headerfiles• Considerthattheprototypeint gcd(int a,int b) isput
intoaheaderfilecalled mathfun.h.• Wecanincorporatethisheaderfileatthetopofmain.c.
#include <stdio.h>#include "mathfun.h"
int main() {printf("GCD: %d\n", gcd(24, 40));return 0;
}
• The#include directivetellsthepreprocessortoreplacethis linewiththecontentsofthefilespecified.– Theanglebracketsareforstandardheaderfilessuchasstdio.h.– Thequotationmarksareforcustom-writtenheaderfilesthatcanbe
foundinthesamedirectoryasthesourcefiles. 74
Recommended