Introduction
Clanguageisaprocess-orientedcomputerprogramminglanguage,whichisdifferentfromobject-orientedprogramminglanguagessuchasC++,C#,andJava.ThedesigngoalofClanguageistoprovideaprogramminglanguagethatcancompileandprocesslow-levelmemoryinasimplemanner,generateonlyasmallamountofmachinecode,andrunwithoutanyoperatingenvironmentsupport.Clanguagedescribesproblemsfasterthanassemblylanguage,withlessworkload,betterreadability,easytodebug,modifyandtransplant,andthecodequalityisequivalenttoassemblylanguage.Clanguageisgenerallyonly10%-20%lessefficientthanthetargetprogramgeneratedbyassemblylanguagecode.Therefore,Clanguagecanwritesystemsoftware.
Atthecurrentstage,inthefieldofprogramming,Clanguageisusedverymuch.Ittakesintoaccounttheadvantagesofhigh-levellanguageandassemblylanguage,andhasgreateradvantagescomparedtootherprogramminglanguages.ComputersystemdesignandapplicationprogrammingaretwomajorareasofClanguageapplication.Atthesametime,theClanguageismoreuniversalandcanbeappliedinmanycomputeroperatingsystems,anditsefficiencyissignificant.
TheClanguagehasacompletetheoreticalsystemthathasgonethroughalonghistoryofdevelopment,andhasapivotalpositioninprogramminglanguages.
DevelopmentHistory
TheClanguagewasborninBellLabsintheUnitedStates.ItwasdesignedbyDennisMacAlistairRitchiebasedontheBlanguagedesignedbyKennethLaneThompson.Thefoundationdeveloped.Afteritsmaindesignwascompleted,ThompsonandRichusedittocompletelyrewriteUNIX.WiththedevelopmentofUNIX,theclanguagehasalsobeencontinuouslyimproved.InordertofacilitatetheoverallpromotionoftheClanguage,manyexperts,scholarsandhardwaremanufacturersjointlyformedtheCLanguageStandardsCommittee,andin1989,thefirstcompleteCstandardwasborn,referredtoas"C89",thatis,"ANSIC"Asof2020,thelatestClanguagestandardis"C18"releasedinJune2018.
TheClanguageisnamedCbecausetheClanguageisderivedfromtheBlanguageinventedbyKenThompson,andtheBlanguageisderivedfromtheBCPLlanguage.
In1967,MartinRichardsofCambridgeUniversitysimplifiedtheCPLlanguage,whichresultedintheBCPL(BasicCombinedProgrammingLanguage)language.
Inthe1960s,KennethLaneThompson(KennethLaneThompson),aresearcheratAT&TBellLaboratoriesintheUnitedStates,hadnothingtodowithhishands.Hewantedtoplaywithhim.Myownvideogamethatsimulatessailinginthesolarsystem-SpaceTravel.Withhisbossonhisback,hefoundanidlesmallcomputer-PDP-7.Butthiscomputerdoesnothaveanoperatingsystem,andthegamemustusesomeofthefunctionsoftheoperatingsystem,sohesetaboutdevelopinganoperatingsystemforthePDP-7.Later,thisoperatingsystemwasnamed-UNICS(UniplexedInformationandComputingService).
In1969,KenThompsonofBellLaboratories,USA,basedontheBCPLlanguage,designedaverysimpleandclosetothehardwareBlanguage(takethefirstletterofBCPL),andwrotethefirstversioninBlanguageTheUNIXoperatingsystem(calledUNICS).
In1971,DennisRich,whoalsolovesSpaceTravel,joinedThompson'sdevelopmentprojecttodevelopUNIXinordertoplaythegameearlier.HismainjobistotransformtheBlanguagetomakeitmoremature.
In1972,DennisRichofBellLabsintheUnitedStatesfinallydesignedanewlanguagebasedontheBlanguage.HetookthesecondletterofBCPLasthenameofthelanguage,ThisistheClanguage.
Inearly1973,themainbodyoftheClanguagewascompleted.ThompsonandRichcouldn'twaittouseittocompletelyrewriteUNIX.Atthistime,thejoyofprogrammingmadethemcompletelyforgetthe"SpaceTravel"anddevotedthemselvestothedevelopmentofUNIXandClanguage.WiththedevelopmentofUNIX,theClanguageitselfisconstantlyimproving.Until2020,variousversionsoftheUNIXkernelandperipheraltoolsstillusetheClanguageasthemaindevelopmentlanguage,andtherearemanycodesinheritedfromthehandsofThompsonandRich.
Duringdevelopment,theyarealsoconsideringportingUNIXtoothertypesofcomputers.ThestrongportabilityoftheClanguageappearshere.Machinelanguageandassemblylanguagearenotportable.Programsdevelopedforx86cannotrunonAlpha,SPARC,ARMandothermachines.TheClanguageprogramcanbeusedonprocessorsofanyarchitecture,aslongastheprocessorofthatarchitecturehasacorrespondingClanguagecompilerandlibrary,andthentheCsourcecodeiscompiledandlinkedintoatargetbinaryfile.Thearchitectureoftheprocessorruns.
In1977,DennisRichpublishedtheClanguagecompiledtext"PortableCLanguageCompiler"thatdoesnotdependonspecificmachinesystems.
TheClanguagecontinuestodevelop.In1982,manypeopleofinsightandtheAmericanNationalStandardsInstitute(ANSI)decidedtoestablishtheCStandardsCommitteetoestablishtheClanguagestandardinordertomaketheClanguagehealthy.Thecommitteeiscomposedofhardwaremanufacturers,compilerandothersoftwaretoolmanufacturers,softwaredesigners,consultants,academics,Clanguageauthorsandapplicationprogrammers.In1989,ANSIpublishedthefirstcompleteClanguagestandard-ANSIX3.159-1989,referredtoas"C89",butpeoplearealsoaccustomedtocallit"ANSIC".C89wasadoptedbytheInternationalStandardOrganization(ISO)unchangedin1990.TheofficialnamegivenbyISOis:ISO/IEC9899,soISO/IEC9899:1990isoftenreferredtoas"C90".In1999,aftermakingsomenecessaryamendmentsandimprovements,ISOissuedanewClanguagestandardnamedISO/IEC9899:1999,or"C99"forshort.OnDecember8,2011,ISOofficiallyreleasedanewstandard,calledISO/IEC9899:2011,or"C11"forshort.
Languagefeatures
Mainfeatures
Clanguageisastructuredlanguagewithclearlevelsandcanbeprogrammedinamodulemanner.Itisveryconducivetothedebuggingoftheprogram,andtheprocessingandperformancecapabilitiesoftheClanguageareverypowerful.Relyingonaverycomprehensiveoperatorandavarietyofdatatypes,theconstructionofvariousdatastructurescanbeeasilycompleted,andthememorycanbedirectlyaccessedthroughthepointertype.Addressinganddirectmanipulationofhardware,soitcanbeusedtodevelopsystemprogramsaswellasapplicationsoftware.ThroughtheresearchandanalysisoftheClanguage,themainfeaturesaresummarizedasfollows:
(1)Conciselanguage
Clanguagecontainsonly9kindsofcontrolstatements,keywordsThereareonly32.Theprogrammingrequirementsarenotstrictandmainlyinlowercaseletters,andmanyunnecessarypartshavebeenstreamlined.Infact,thesentencecompositionislessrelatedtothehardware,andtheClanguageitselfdoesnotprovidehardware-relatedinputandoutput,filemanagementandotherfunctions.Ifsuchfunctionsareneeded,theyneedtobeprogrammedwithvariouslibrariessupportedbythecompilationsystem.,Sotheclanguagehasaveryconcisecompilationsystem.
(2)Structuredcontrolstatements
Clanguageisastructuredlanguage,andthecontrolstatementsprovidedhavestructuredfeatures,suchasforstatements,if...Elsestatementandswitchstatement,etc.Itcanbeusedtorealizethelogiccontrolofthefunctionandfacilitatetheprocess-orientedprogramming.
(3)Richdatatypes
Clanguagecontainsawiderangeofdatatypes,includingnotonlytraditionalcharacter,integer,floating-point,arraytypesandotherdatatypes,Italsohasdatatypesthatotherprogramminglanguagesdonothave.Thepointertypedataisthemostflexibletouse,andvariousdatastructurescanbecalculatedthroughprogramming.
(4)Richoperators
TheClanguagecontains34operators.Ittreatsassignments,parentheses,etc.asoperatorstooperate,makingtheexpressiontypeoftheCprogramAndoperatortypesareveryrich.
(5)Thephysicaladdresscanbedirectlymanipulated
TheClanguageallowsdirectreadingandwritingofthehardwarememoryaddress,whichcanrealizethemainfunctionsofassemblylanguageandcanbedirectlymanipulatedhardware.Clanguagenotonlyhasthegoodcharacteristicsofhigh-levellanguages,butalsocontainsmanyadvantagesoflow-levellanguages,soithasawiderangeofapplicationsinthefieldofsystemsoftwareprogramming.
(6)Thecodehasgoodportability
Clanguageisaprocess-orientedprogramminglanguage,usersonlyneedtopayattentiontotheproblemtobesolved,withouthavingtospendtoomuchtimeMoreenergytounderstandtherelevanthardware,andfordifferenthardwareenvironments,thecodeisbasicallythesamewhenusingtheClanguagetoachievethesamefunction,andthetransplantationcanbecompletedwithoutoronlyafewchanges,whichmeansthatforacomputerThewrittenCprogramcanbeeasilyrunonanothercomputer,whichgreatlyreducestheworkintensityofprogramtransplantation.
(7)Programsthatcangeneratehigh-qualityandhigh-efficiencytargetcodeexecution
Comparedwithotherhigh-levellanguages,Clanguagecangeneratehigh-qualityandhigh-efficiencytargetcodes,soItisusuallyusedtowriteembeddedsystemprogramsthatrequirehighcodequalityandexecutionefficiency.
Uniquefeatures
Clanguageisthemostuniversallyapplicablecomputerprogrameditinglanguage.Itcannotonlyexertthefunctionsofhigh-levelprogramminglanguage,butalsohastheadvantagesofassemblylanguage.Therefore,ithasitsownuniquecharacteristicscomparedtootherprogramminglanguages.Itisembodiedinthefollowingthreeaspects:
First,extensiveness.ThesizeoftheoperationrangeoftheClanguagedirectlydeterminesitsprosandcons.Clanguagecontains34kindsofoperators,sothescopeofoperationisbeyondmanyotherlanguages,andtheexpressionoftheresultofitsoperationisalsoveryrich.Inaddition,theClanguagecontainsavarietyofdatastructureformssuchascharactertypeandpointertype,soitcanalsohandlelargerdatastructureoperations.
Second,simplicity.Ninetypesofcontrolstatementsand32keywordsarethebasicfeaturesoftheClanguage,whichmakesitwidelyapplicableincomputerapplicationprogramming.Itcannotonlyapplytotheoperationofthemajorityofprogrammers,improvetheirworkefficiency,butalsosupportAdvancedprogrammingavoidsthecumbersomelanguageswitching.
Thirdly,thestructureisperfect.Clanguageisastructuredlanguage.Itcanrealizemodularizedapplicationsintheformofmodularunits.Ithassignificantadvantagesinsystemdescription.Atthesametime,thisfeatureenablesittoadapttoavarietyofdifferentprogrammingrequirementsandexecuteefficient.
Disadvantages
1.ThedisadvantagesoftheClanguagearemainlytheweakdataencapsulation,whichmakesChaveabigflawindatasecurity,whichisalsoCandC++Onebigdifference.
2.ThegrammaticalrestrictionofClanguageisnottoostrict,andthetyperestrictionofvariablesisnotstrict,whichaffectsthesafetyoftheprogram,anddoesnotcheckthearraysubscriptbeyondtheboundary.Fromtheapplicationpointofview,Clanguageismoredifficulttomasterthanotherhigh-levellanguages.Inotherwords,peoplewhouseClanguagearerequiredtobemoreproficientinprogramming.
Languagecomposition
Basiccomposition
Datatype
ThedatatypeofCincludes:integer(short,int,long,longlong),charactertype(char),realtypeorfloatingpointtype(single-precisionfloatanddouble-precisiondouble),enumerationtype(enum),arraytype,structuretype(struct),sharedBodytype(union),pointertypeandvoidtype(void).
Constantsandvariables
Thevalueofaconstantcannotbechanged,andthenameofasymbolicconstantisusuallycapitalized.
Avariableistheamountwhosevaluecanbechangedwithanidentifierasitsname.Anidentifierisasequenceofletters,numbersorunderscoresstartingwithaletterorunderscore.Pleasenotethatthefirstcharactermustbealetterorunderscore,otherwiseitisanillegalvariablename.Variablesareallocatedcorrespondingstorageunitsatcompiletime.
Array
Ifavariablenameisfollowedbyabracketwithanumber,thedeclarationisanarraydeclaration.Stringisalsoanarray.TheyendwithASCIINULLastheendofthearray.Itisimportanttonotethattheindexvalueinthebracketsiscountedfrom0.
Pointer
Ifavariableisdeclaredwith*infrontofit,itmeansthatitisapointervariable.Inotherwords,thevariablestoresanaddress,and*(herespecificallyreferstotheunaryoperator*,thesamebelow.Thereisalsoabinaryoperator*intheClanguage)isacontentoperator,whichmeanstotakethismemoryaddressThecontentstoredin.PointerisoneofthemainfeaturesthatdistinguishesClanguagefromothercontemporaryhigh-levellanguages.
Pointerscanbenotonlytheaddressesofvariables,butalsotheaddressesofarrays,arrayelements,andfunctions.Usingpointersasformalparameterscangetmorethanonereturnvalueinthecallingprocessofthefunction,unlikereturn(z),whichcanonlygetonereturnvalue.
Pointersareadouble-edgedsword.Manyoperationscanbeexpressednaturallythroughpointers,butincorrectorexcessiveuseofpointerswillbringalotofpotentialerrorstotheprogram.
String
Clanguagestringsareactuallychararraysendingwith'\0'characters,andtheuseofcharactertypesdoesnotrequirereferencetothelibrary,ButtheuseofstringsrequiressomefunctionsintheCstandardlibraryformanipulatingstrings.Theyaredifferentfromcharacterarrays.Tousethesefunctions,youneedtoquotetheheaderfile.
Fileinput/output
InClanguage,inputandoutputareimplementedthroughasetoffunctionsinthestandardlibrary.InANSIC,thesefunctionsaredefinedintheheaderfile;.
Standardinput/output
Therearethreestandardinput/outputthatarepredefinedbythestandardI/Olibrary:
stdinstandardinput
stdoutstandardoutput
stderrinputandoutputerror
Calculation
TheoperationofClanguageisveryflexible,thefunctionisveryrich,andtheoperationtypeFarmorethanotherprogramminglanguages.Intermsofexpressions,itismoreconcisethanotherprogramminglanguages.Forexample,addition,subtraction,commaoperationsandtrinocularoperationsmakeexpressionseasier,butbeginnersoftenfindsuchexpressionsdifficulttoread.ThekeyreasonisthatTheoperatorsandtheorderofoperationsarenotfullyunderstood.Whenmultipledifferentoperationsformanoperationexpression,thatis,whenmultipleoperatorsappearinanexpression,theorderofprecedenceandcombinationrulesofoperationswillbecomeveryimportant.
Keywords
Keywordsarealsocalledreservedwords,whicharewordsthathavebeenusedbytheClanguageitselfandcannotbeusedforotherpurposes.Forexample,keywordscannotbeusedasidentifierssuchasvariablenamesandfunctionnames.
Datatypekeyword
short:Modifiedint,shortintegerdata,modifiedintcanbeomitted.(IntroducedintheK&Rperiod)
long:Modifiedint,longintegerdata,modifiedintcanbeomitted.(IntroducedintheK&Rperiod)
longlong:Modifiedint,superlongintegerdata,modifiedintcanbeomitted.(NewtoC99standard)
signed:Modifiedintegerdata,signeddatatype.(NewtoC89standard)
unsigned:Modifiedintegerdata,unsigneddatatype.(IntroducedduringtheK&Rperiod)
restrict:Usedtorestrictandconstrainthepointer,andindicatethatthepointeristheinitialandonlyonetoaccessadataobjectWay.(NewtoC99standard)
Complextypekeywords
struct:structuredeclaration.(IntroducedduringtheK&Rperiod)
union:Unionstatement.(IntroducedduringtheK&Rperiod)
enum:Enumerationdeclaration.(NewtoC89standard)
typedef:Declaretypealias.(IntroducedintheK&Rperiod)
sizeof:Getthesizeofaspecifictypeoraspecifictypeofvariable.(IntroducedduringtheK&Rperiod)
inline:Inlinefunctionsareusedtoreplacemacrodefinitionsandwillbeexpandedwhereveritiscalled.(NewtoC99standard)
Storagelevelkeywords
auto:designatedasautomaticvariables,automaticallyassignedbythecompilerAndrelease.Usuallyallocatedonthestack.Contrarytostatic.Whenthevariableisnotspecified,itdefaultstoauto.(IntroducedintheK&Rperiod)
static:Specifyasastaticvariableandallocateitinthestaticvariablearea.Whenmodifyingafunction,specifythefunctionscopetobeinsidethefile.(IntroducedduringtheK&Rperiod)
register:Specifyasaregistervariable,itisrecommendedthatthecompilerstorethevariableintheregisterforuse,ormodifythefunctionparameters,itisrecommendedthatthecompilerpassParametersarepassedinregistersinsteadofthestack.(IntroducedintheK&Rperiod)
extern:Specifythecorrespondingvariableasanexternalvariable,thatis,markthedefinitionofthevariableorfunctioninanotherfile,promptingthecompilertoencounterthisvariableLookfordefinitionsinothermoduleswhensumfunctions.(IntroducedduringtheK&Rperiod)
const:Thespecifiedvariablecannotbechangedbythecurrentthread(butitmaybechangedbythesystemorotherthreads).(NewtoC89standard)
volatile:Thevalueofthespecifiedvariablemaybechangedbythesystemorotherthreads,forcingthecompilertoobtainthevalueofthevariablefrommemoryeverytime.Preventthecompilerfromoptimizingthisvariableintoaregistervariable.(NewtoC89standard)
Processcontrolkeywords
Jumpstructure
return:Usedinthebodyofafunctiontoreturnaspecificvalue(ifitisofvoidtype,thefunctionvalueisnotreturned).(IntroducedduringK&Rperiod)
continue:Endthecurrentcycleandstartthenextcycle.(IntroducedduringtheK&Rperiod)
break:Jumpoutofthecurrentlooporswitchstructure.(IntroducedduringtheK&Rperiod)
goto:Unconditionaljumpstatement.(IntroducedduringtheK&Rperiod)
Branchstructure
if:Conditionalstatement,noneedtoputasemicolonafterit.(IntroducedduringK&Rperiod)
else:Negativebranchofconditionalstatement(usedinconjunctionwithif).(IntroducedduringtheK&Rperiod)
switch:switchstatement(multiplebranchstatement).(IntroducedduringtheK&Rperiod)
case:Thebranchmarkintheswitchstatement,usedinconjunctionwithswitch.(IntroducedduringtheK&Rperiod)
default:The"other"branchintheswitchstatement,optional.(IntroducedduringtheK&Rperiod)
Grammaticalstructure
Sequentialstructure
Theprogramdesignofsequencestructureisthesimplest,aslongasJustwritethecorrespondingstatementsintheorderofsolvingtheproblem,andtheorderofexecutionisfromtoptobottom,inturn.
Forexample:a=3,b=5,nowexchangethevaluesofaandb.Thisproblemislikeexchangingthewaterintwocups.Ofcourse,athirdcupisused.IfthethirdIfthecupisc,thenthecorrectprogramis:c=a;a=b;b=c,theexecutionresultisa=5,b=c=3,ifyouchangetheorder,write:a=b;c=a;b=c;Thentheexecutionresultbecomesa=b=c=5,whichcannotachievetheexpectedpurpose,andbeginnersaremostlikelytomakethiskindofmistake.Thesequencestructurecanbeusedindependentlytoformasimplecompleteprogram.Thecommoninput,calculation,andoutputthree-stepprogramisthesequencestructure.Forexample,tocalculatetheareaofacircle,thesequenceofstatementsintheprogramistheradiusroftheinputcircle,andthecalculations=3.14159*r*r,theareasoftheoutputcircle.However,inmostcases,thesequencestructureisusedasapartoftheprogramandformsacomplexprogramtogetherwithotherstructures,suchascompoundstatementsinbranchstructures,loopbodiesinloopstructures,andsoon.
Selectthestructure
Althoughtheprogramofthesequencestructurecansolvetheproblemsofcalculationandoutput,itcannotbejudgedandthenselected.Forproblemsthatneedtobejudgedfirstandthenselected,aselectionstructureshouldbeused.Theexecutionoftheselectionstructureisbasedoncertainconditionstoselecttheexecutionpath,ratherthanstrictlyinaccordancewiththephysicalorderofthestatements.Thekeytotheprogramdesignmethodofselectingthestructureistoconstructappropriatebranchconditionsandanalyzetheprogramflow,andselecttheappropriateselectionstatementaccordingtothedifferentprogramflow.Theselectedstructureissuitableforcalculationswithconditionaljudgmentssuchaslogicorrelationalcomparison.Whendesigningsuchprograms,itisoftennecessarytodrawtheprogramflowchartfirst,andthenwritethesourceprogramaccordingtotheprogramflow.Inthisway,theprogramdesignanalysisisseparatedfromthelanguage.Makestheproblemsimpleandeasytounderstand.Theprogramflowchartisbasedontheprogramexecutionflowchartdrawnbytheproblem-solvinganalysis.
Cyclicstructure
Thecyclicstructurecanreducetheworkloadofrepetitivewritingofthesourceprogram,andisusedtodescribetheproblemofrepeatedexecutionofacertainalgorithm.ThisisprogramdesignTheprogramstructurethatcangivefullplaytocomputerspecialtiesinClanguageprovidesfourkindsofloops,namelygotoloop,whileloop,dowhileloopandforloop.Thefourloopscanbeusedtodealwiththesameproblem.Undernormalcircumstances,theycanreplaceeachother.However,itisgenerallynotrecommendedtousegotoloops,becauseforciblychangingtheorderoftheprogramwilloftenbringunexpectederrorstotheoperationoftheprogram.
Specialattentionshouldbepaidtotheendingstatement(thatis,thechangeoftheloopvariablevalue)intheloopbody,otherwiseitmaybecomeanendlessloop,whichisacommonmistakeofbeginners.
Thesimilaritiesanddifferencesofthethreeloops:whenusingwhileanddowhileloops,theinitializationofloopvariablesshouldbebeforetheloopbody,andtheforloopisgenerallycarriedoutinstatement1;whileloopandforloopTheexpressionisjudgedfirst,andthentheloopbodyisexecuted.Thedowhileloopexecutestheloopbodyfirstandthenjudgestheexpression.Thatistosay,theloopbodyofdowhileisexecutedatleastonce,whilethewhileloopandformaynotbeexecutedonce..Alsonotethatthesethreetypesofloopscanallusethebreakstatementtojumpoutoftheloop,andusethecontinuestatementtoendtheloop.Theloopformedbythegotostatementandtheifcannotbecontrolledbythebreakandcontinuestatements.
Sequentialstructure,branchstructureandloopstructurearenotisolatedfromeachother.Therecanbebranchesandsequencestructuresinloops,andloopsandsequencestructuresinbranches.Infact,nomatterwhichstructure,itcanbegeneralizedThinkofthemasonesentence.Intheactualprogrammingprocess,thesethreestructuresareoftencombinedtoimplementvariousalgorithmsanddesigncorrespondingprograms.However,theprogrammingproblemsarerelativelylarge.Theprogramswrittenareoftenverylongandthestructureisrepeated,resultinginpoorreadabilityanddifficulty.UnderstandthatthewaytosolvethisproblemistodesigntheCprogramintoamodularstructure.
Specificcontent:
Forloop
TheforloopstructureisthemostdistinctiveinClanguageTheloopstatementisthemostflexibleandconvenienttouse.Itsgeneralformis:for(expression1;expression2;expression3)loopbodystatement.(Amongthem;cannotbeomitted)
Expression1isaninitialvalueexpression,whichisusedtoassigninitialvaluestotheloopvariablesbeforetheloopstarts.
Expression2isaloopcontrollogicexpression,whichcontrolstheconditionofloopexecutionanddeterminesthenumberofloops.
Expression3modifiestheexpressionfortheloopcontrolvariable,whichmakestheforlooptendtoend.
Theloopbodystatementisastatementthatisexecutedrepeatedlywhentheloopcontrolconditionissatisfied.
Butintheentireforloopprocess,expression1isonlycalculatedonce,expression2andexpression3maybecalculatedmultipletimes,ormaynotbecalculatedonce.Thebodyoftheloopmaybeexecutedmultipletimes,oritmaynotbeexecutedonce.
Executeexpression2first,thenexecutetheloopstructure,andfinallyexpression3,andkeeploopinglikethis.
TheforloopstatementisthemostpowerfulstatementintheClanguage,anditcanevenreplaceotherloopstatementstoacertainextent.
do
doloopstructure,do1while(2);executionorderis1->2->1...loop,2isthecyclecondition.
while
whileloopstructure,theexecutionorderofwhile(1)2;is1->2->1...loop,1istheloopcondition
Theaboveloopstatement,whentheloopconditionexpressionistrue,theloopwillcontinue,andifitisfalse,itwilljumpoutoftheloop.
Function
Cprogramiscomposedofasetofvariablesorexternalobjectsoffunctions.Afunctionisaself-containedexecutioncodesegmentthatcompletescertainrelatedfunctions.Wecanthinkofafunctionasa"blackbox",youcangettheresultaslongasyousendthedatain,andtheexternalprogramdoesn'tknowhowthefunctionworksinside.Whattheexternalprogramknowsislimitedtowhatisinputtothefunctionandwhatthefunctionoutputs.Functionsprovideameansofprogrammingtomakeiteasytoread,write,understand,eliminateerrors,modify,andmaintain.
ThenumberoffunctionsinaCprogramisactuallyunlimited.Ifthereisanyrestriction,thatis,theremustbeatleastonefunctioninaCprogram,andtheremustbeoneandonlyoneofthemThefunctionnamedmain,thisfunctioniscalledthemainfunction,andtheentireprogramisexecutedfromthismainfunction.
Clanguageprogramsencourageandencouragepeopletodivideabigproblemintosub-problems,whichcorrespondstosolvingasub-problemandcompileafunction.Therefore,ClanguageprogramsgenerallyconsistofalargenumberofsmallfunctionsratherthanafewLargefunctionsconstitutetheso-called"smallfunctionsconstitutealargeprogram."Theadvantageofthisisthateachpartisfullyindependentofeachotherandthetaskissingle.Therefore,thesesufficientlyindependentsmallmodulescanalsobeusedasasmall"component"withafixedspecificationtoformanewlargeprogram.
ForsomanyyearsinthedevelopmentofClanguage,thereareavastarrayofsystemsandprogramsdevelopedinClanguage.Alotoflibraryfunctionsthatcanbeuseddirectlyhavebeenaccumulatedwhiledeveloping.
ANSICprovidesstandardClanguagelibraryfunctions.
TurboC2.0,whichispreferredbyClanguagebeginners,providesmorethan400runtimefunctions,eachofwhichperformsaspecificfunction,whichuserscancallatwill.Thesefunctionsaregenerallydividedintoinputandoutputfunctions,mathematicalfunctions,stringandmemoryfunctions,functionsrelatedtoBIOSandDOS,characterscreenandgraphicsfunctionfunctions,processcontrolfunctions,directoryfunctions,etc.
TheWindowsSDKprovidedbytheWindowssystemcontainsthousandsoffunctionsrelatedtoWindowsapplicationdevelopment.Otheroperatingsystems,suchasLinux,alsoprovidealargenumberoffunctionsforapplicationdeveloperstocall.
Asaprogrammer,youshouldtrytobefamiliarwiththefunctionsofthetargetplatformlibraryfunctions.Inthisway,youcandevelopapplicationsforaspecificplatformwithease.Forexample,asaWindowsapplicationdeveloper,youshouldbeasfamiliarwiththeWindowsSDKaspossible;asaLinuxapplicationdeveloper,youshouldbeasfamiliarwithLinuxsystemcallsandPOSIXfunctionspecificationsaspossible.
Operationsymbol
Whatismorespecialisthatthebitshiftright(>>)operatorcanbearithmetic(complementthemostsignificantbitontheleftend)orlogic(complement0ontheleftend)Displacement.Forexample,if11100011isshiftedtotherightby3bits,thearithmeticshifttotherightbecomes11111100,andthelogicalshifttotherightbecomes00011100.Sincetherightshiftofarithmeticbitsismoresuitableforprocessingnegativeintegers,almostallcompilersshiftrightarithmeticbits.
Theprecedenceofoperatorsfromhightolowisroughly:unaryoperators,arithmeticoperators,relationaloperators,logicaloperators,conditionaloperators,assignmentoperators(=)andcommaoperators.
Programmingdevelopment
Compiler
GCC,anopensourceandfreecompilerdevelopedbytheGNUorganization
MinGW,undertheWindowsoperatingsystemGCC
Clang,theopensourceBSDprotocol-basedLLVM-basedcompiler
VisualC++::cl.exe,thecompilerthatcomeswithMicrosoftVC++
integrationDevelopmentenvironment
Code::Blocks,opensourceandfreeC/C++IDE
CodeLite,opensource,cross-platformC/C++integrateddevelopmentenvironment
Dev-C++,portableC/C++IDE
C-Free
LightTable
VisualStudioseries
Sampleprogram
Thefollowingisasimpleprogramthatprintsthestring"Hello,world!"onthestandardoutputdevice(stdout).Asimilarprogramisusuallyusedasthefirstprogramwhenlearningaprogramminglanguage:
#includeintmain(){printf("Hello,World!\n");return0;}
Thefirstlineoftheprogram#includeisapreprocessordirective,tellingtheCcompilertoincludethestdio.hfilebeforetheactualcompilation.
Thenextlineintmain()isthemainfunction,andtheprogramexecutesfromhere.
Thenextlineprintf(...)isanotherfunctionavailableinCthatwilldisplaythemessage"Hello,World!"onthescreen.
Thenextlinereturn0;Terminatethemain()functionandreturnthevalue0.
#includeintmain{voidmove(int*xa,int*xb);inta,b;printf("Pleaseentertwonumbersa,b:");scanf("%d,%d",&a,&b);move(&a,&b);printf("a=%d,b=%d\n",a,b);return0;}voidmove(int*xa,int*xb){inta;a=*xa;*xa=*xb;*xb=a;}
1.Thethirdlineisthedeclarationofthefunction,whichdeclaresafunctionwithnoreturnvaluewithtwopointerparameters.Sincethedefinitionofthefunctionisunderthecallingfunction,itmustbedeclared.
2.Thefourthlineisthedefinitionofvariables,whichdefinestwointegervariables.
3.Entertwonumbersonthesixthline,whichmustbeenteredwithacommalike1,0.Puttwonumbersintovariablesaandb."&"istheaddressoperator.
4.Theseventhlinecallsthemovefunctiontoconvertthevaluesofthetwovariables.
5.Afterthemainfunctionisthedefinitionofthemovefunction.
Ascanbeseenfromthisexample,pointervariablescangetmorereturnvalues,whichisveryconvenient.