Home Техника c език

c език



Introduction

Clanguageisaprocess-orientedcomputerprogramminglanguage,whichisdifferentfromobject-orientedprogramminglanguages​​suchasC++,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.

Езикът продължава да се развива. През 1982 г. много проницателни хора и Американският институт за национални стандарти (ANSI) решиха да създадат Комитет по стандартите, който да създаде стандарта за езика, за да направи езика здрав. Комитетът се състои от производители на хардуер, компилатори и други производители на софтуерни инструменти ,софтуерни дизайнери, консултанти, академици, автори на езици и програмисти на приложения. През 1989 г. ANSI публикува първия пълен стандарт за език - ANSIX3.159-1989, наричан "C89", но хората наистина са свикнали да го наричат ​​"ANSIC". C89 беше приет от Международната организация за стандартизация (ISO) непроменен 1990 г .Официалното име, дадено от ISO, е: ISO/IEC9899, ​​така че ISO/IEC9899:1990се нарича "C90". През 1999 г., след като направи някои необходими изменения и подобрения, ISO издаде нов стандарт за език, наречен ISO/IEC9899:1999 или "C99" за кратко. На 8 декември, 2011 г., ISO официално пусна нов стандарт, наречен ISO/IEC9899:2011 или "C11" на кратко.

Languagefeatures

Mainfeatures

Clanguageisastructuredlanguagewithclearlevelsandcanbeprogrammedinamodulemanner.Itisveryconducivetothedebuggingoftheprogram,andtheprocessingandperformancecapabilitiesoftheClanguageareverypowerful.Relyingonaverycomprehensiveoperatorandavarietyofdatatypes,theconstructionofvariousdatastructurescanbeeasilycompleted,andthememorycanbedirectlyaccessedthroughthepointertype.Addressinganddirectmanipulationofhardware,soitcanbeusedtodevelopsystemprogramsaswellasapplicationsoftware.ThroughtheresearchandanalysisoftheClanguage,themainfeaturesaresummarizedasfollows:

(1) Кратък език

Clanguagecontainsonly9kindsofcontrolstatements,keywordsThereareonly32.Theprogrammingrequirementsarenotstrictandmainlyinlowercaseletters,andmanyunnecessarypartshavebeenstreamlined.Infact,thesentencecompositionislessrelatedtothehardware,andtheClanguageitselfdoesnotprovidehardware-relatedinputandoutput,filemanagementandotherfunctions.Ifsuchfunctionsareneeded,theyneedtobeprogrammedwithvariouslibrariessupportedbythecompilationsystem.,Sotheclanguagehasaveryconcisecompilationsystem.

(2) Структурирани отчети за контрол

Clanguageisastructuredlanguage,andthecontrolstatementsprovidedhavestructuredfeatures,suchasforstatements,if...Elsestatementandswitchstatement,etc.Itcanbeusedtorealizethelogiccontrolofthefunctionandfacilitatetheprocess-orientedprogramming.

(3) Богати типове данни

Clanguagecontainsawiderangeofdatatypes,includingnotonlytraditionalcharacter,integer,floating-point,arraytypesandotherdatatypes,Italsohasdatatypesthatotherprogramminglanguages​​donothave.Thepointertypedataisthemostflexibletouse,andvariousdatastructurescanbecalculatedthroughprogramming.

(4) Богати оператори

TheClanguagecontains34operators.Ittreatsassignments,parentheses,etc.asoperatorstooperate,makingtheexpressiontypeoftheCprogramAndoperatortypesareveryrich.

(5)Физическият адрес може да бъде манипулиран директно

TheClanguageallowsdirectreadingandwritingofthehardwarememoryaddress,whichcanrealizethemainfunctionsofassemblylanguageandcanbedirectlymanipulatedhardware.Clanguagenotonlyhasthegoodcharacteristicsofhigh-levellanguages,butalsocontainsmanyadvantagesoflow-levellanguages,soithasawiderangeofapplicationsinthefieldofsystemsoftwareprogramming.

(6)Кодът има добра преносимост

Clanguageisaprocess-orientedprogramminglanguage,usersonlyneedtopayattentiontotheproblemtobesolved,withouthavingtospendtoomuchtimeMoreenergytounderstandtherelevanthardware,andfordifferenthardwareenvironments,thecodeisbasicallythesamewhenusingtheClanguagetoachievethesamefunction,andthetransplantationcanbecompletedwithoutoronlyafewchanges,whichmeansthatforacomputerThewrittenCprogramcanbeeasilyrunonanothercomputer,whichgreatlyreducestheworkintensityofprogramtransplantation.

(7) Програми, които могат да генерират висококачествено и високоефективно изпълнение на целеви кодове

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.

Недостатъци

1.Недостатъкът на езика е главно слабото капсулиране на данни, което прави Chave голям пропуск в сигурността на данните, което също може да е голяма разлика в C++.

2.ThegrammaticalrestrictionofClanguageisnottoostrict,andthetyperestrictionofvariablesisnotstrict,whichaffectsthesafetyoftheprogram,anddoesnotcheckthearraysubscriptbeyondtheboundary.Fromtheapplicationpointofview,Clanguageismoredifficulttomasterthanotherhigh-levellanguages.Inotherwords,peoplewhouseClanguagearerequiredtobemoreproficientinprogramming.

Езикова композиция

Основна композиция

Тип данни

ThedatatypeofВключва:integer(short,int,long,longlong),charactertype(char),realtypeorfloatingpointtype(single-precisionfloatanddouble-precisiondouble),enumerationtype(enum),arraytype,structuretype(struct),sharedBodytype(union),pointertypeandvoidtype(void ).

Константи и променливи

Thevalueofaconstantcannotbechanged,andthenameofasymbolicconstantisusuallycapitalized.

Avariableistheamountwhosevaluecanbechangedwithanidentifierasitsname.Anidentifierisasequenceofletters,numbersorunderscoresstartingwithaletterorunderscore.Pleasenotethatthefirstcharactermustbealetterorunderscore,otherwiseitisanillegalvariablename.Variablesareallocatedcorrespondingstorageunitsatcompiletime.

Масив

Ifavariablenameisfollowedbyabracketwithanumber,thedeclarationisanarraydeclaration.Stringisalsoanarray.TheyendwithASCIINULLastheendofthearray.Itisimportanttonotethattheindexvalueinthebracketsiscountedfrom0.

Показател

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.

Низ

Clanguagestringsareactuallychararraysendingwith'\0'characters,andtheuseofcharactertypesdoesnotrequirereferencetothelibrary,ButtheuseofstringsrequiressomefunctionsintheCstandardlibraryformanipulatingstrings.Theyaredifferentfromcharacterarrays.Tousethesefunctions,youneedtoquotetheheaderfile.

Файлов вход/изход

InClanguage,inputandoutputareimplementedthroughasetoffunctionsinthestandardlibrary.InANSIC,thesefunctionsaredefinedintheheaderfile;.

Стандартен вход/изход

Има три стандартни входа/изхода, които са предварително дефинирани от стандартната I/Olibrary:

стандартен вход

стандартен изход стандартен изход

грешка при stderrinputandoutput

Изчисляване

TheoperationofClanguageisveryflexible,thefunctionisveryrich,andtheoperationtypeFarmorethanotherprogramminglanguages.Intermsofexpressions,itismoreconcisethanotherprogramminglanguages.Forexample,addition,subtraction,commaoperationsandtrinocularoperationsmakeexpressionseasier,butbeginnersoftenfindsuchexpressionsdifficulttoread.ThekeyreasonisthatTheoperatorsandtheorderofoperationsarenotfullyunderstood.Whenmultipledifferentoperationsformanoperationexpression,thatis,whenmultipleoperatorsappearinanexpression,theorderofprecedenceandcombinationrulesofoperationswillbecomeveryimportant.

Keywords

Keywordsarealsocalledreservedwords,whicharewordsthathavebeenusedbytheClanguageitselfandcannotbeusedforotherpurposes.Forexample,keywordscannotbeusedasidentifierssuchasvariablenamesandfunctionnames.

Ключова дума тип данни

кратко:Модифицирана int,кратка целочислена информация,модифицирана цел може да бъде пропусната.(Въведено в периода K&R)

long:Modifiedint,longintegerdata,modifiedint могат да бъдат пропуснати.(Въведено в периода K&R)

longlong:Modifiedint,superlongintegerdata,modifiedintcanbeoutmitted.(NewtoC99standard)

подписан: Модифицирани цели числа, тип данни със знак. (Нов стандарт C89)

unsigned: Модифицирани цели числа, неподписан тип данни. (Въведено по време на K&Rпериода)

ограничаване:Използва се за ограничаване и ограничаване на указателя и посочване, че указателят е първоначалният и само един за достъп до обект с данни. (Ново към стандарт C99)

Ключови думи от сложен тип

struct:structuredeclaration.(Въведено по време на K&Rпериода)

съюз: Декларация на съюза. (Въведено по време на K&Rпериода)

enum: Декларация за изброяване. (NewtoC89standard)

typedef: Деклариране на псевдоним на тип. (Въведено в K&Rпериода)

sizeof: Получава размера на конкретен тип или конкретен тип променлива. (Въведено по време на K&Rпериода)

вградени:Вградените функции се използват за заместване на макродефиниции и ще бъдат разширени навсякъде, където е извикана. (Ново към стандарт C99)

Ключови думи за ниво на съхранение

auto:обозначени като автоматични променливи, автоматично присвоени от компилатора Andrelease. Обикновено се разпределят в стека. За разлика от статичните. Когато променливата не е посочена, по подразбиране е автоматично. (Въведено в K&Rпериода)

статичен: Посочете като статична променлива и я разпределете в областта на статичната променлива. Когато модифицирате функция, посочете функционалния обхват да бъде вътре във файла. (Въведено по време на K&Rпериода)

register:Specifyasaregistervariable,itisrecommendedthatthecompilerstorethevariableintheregisterforuse,ormodifythefunctionparameters,itisrecommendedthatthecompilerpassParametersarepassedinregistersinsteadofthestack.(IntroducedintheK&Rperiod)

extern:Specifythecorrespondingvariableasanexternalvariable,thatis,markthedefinitionofthevariableorfunctioninanotherfile,promptingthecompilertoencounterthisvariableLookfordefinitionsinothermoduleswhensumfunctions.(IntroducedduringtheK&Rperiod)

const: Посочената променлива не може да бъде променена от текущата нишка (но може да бъде променена от системата или други нишки). (Ново в стандарта C89)

volatile:Thevalueofthespecifiedvariablemaybechangedbythesystemorotherthreads,forcingthecompilertoobtainthevalueofthevariablefrommemoryeverytime.Preventthecompilerfromoptimizingthisvariableintoaregistervariable.(NewtoC89standard)

Ключови думи за контрол на процеса

Скоктура

връщане: Използва се в тялото на функцията за връщане на конкретна стойност (ако е празен тип, стойността на функцията не е върната). (Въведено по време на K&Rпериод)

продължи: Край на текущия цикъл и начало на следващия цикъл. (Въведено по време на K&Rпериода)

прекъсване: Прескачане на структурата на превключвателя на текущата верига. (Въведено по време на K&Rпериода)

goto: Безусловен преход. (Въведено по време на K&Rпериода)

Клонова структура

ако:Условен оператор,няма нужда да поставяте точка и точка след това.(Въведено по време на K&Rпериод)

else: Отрицателен клон на условен израз (използван във връзка с if). (Въведено по време на K&Rпериода)

switch:switchstatement(multiplebranchstatement).(Въведено по време на K&Rпериода)

случай: Знакът за разклонение в израза на превключвателя, използван във връзка с превключвател. (Въведено през периода K&R)

по подразбиране: „Другият“ клон в израза за превключване, по избор. (Въведен по време на K&Rпериода)

Граматична структура

Последователна структура

Theprogramdesignofsequencestructureisthesimplest,aslongasJustwritethecorrespondingstatementsintheorderofsolvingtheproblem,andtheorderofexecutionisfromtoptobottom,inturn.

Например:a=3,b=5,сега разменяместойностите​​наиb.Този проблем предполага смяна наводата в две чаши.Разбира се,използвана е трета чаша.Ако третата,ако е чашатаc,тогава правилната програма е:c=a;a=b;b=c,резултатът от изпълнението е=5,b=c=3, ако промените реда, напишете: a=b;c=a;b=c;Тогава резултатът от изпълнението става=b=c=5, което не може да постигне очакваната цел и е най-вероятно начинаещите да допуснат тази грешка. Тази структура на последователността може да се използва независимо за формиране на проста пълна програма.Общата програма за въвеждане, изчисление и изход от три стъпки е структурата на последователността. Например, за да се изчисли площта на​​окръжността, последователността от изрази в радиуса на програмата на въведената окръжност и изчисленията=3,14159 *r*r,областта на изходния кръг. В повечето случаи обаче тази структура на последователност се използва като част от програмата и образува сложна програма заедно с други структури, като съставни изрази в структури на клонове, тела на цикъл в структури на цикъл и т.н.

Изберете структурата

Althoughtheprogramofthesequencestructurecansolvetheproblemsofcalculationandoutput,itcannotbejudgedandthenselected.Forproblemsthatneedtobejudgedfirstandthenselected,aselectionstructureshouldbeused.Theexecutionoftheselectionstructureisbasedoncertainconditionstoselecttheexecutionpath,ratherthanstrictlyinaccordancewiththephysicalorderofthestatements.Thekeytotheprogramdesignmethodofselectingthestructureistoconstructappropriatebranchconditionsandanalyzetheprogramflow,andselecttheappropriateselectionstatementaccordingtothedifferentprogramflow.Theselectedstructureissuitableforcalculationswithconditionaljudgmentssuchaslogicorrelationalcomparison.Whendesigningsuchprograms,itisoftennecessarytodrawtheprogramflowchartfirst,andthenwritethesourceprogramaccordingtotheprogramflow.Inthisway,theprogramdesignanalysisisseparatedfromthelanguage.Makestheproblemsimpleandeasytounderstand.Theprogramflowchartisbasedontheprogramexecutionflowchartdrawnbytheproblem-solvinganalysis.

Циклична структура

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.

Конкретно съдържание:

Forloop

Структурата на forloop е най-отличителната в езика. Инструкцията за цикъл е най-гъвкава и удобна за използване. Общата му форма е: for(expression1;expression2;expression3)loop body statement. (Сред тях; не може да бъде пропуснат)

Expression1isaninitialvalueexpression,whichisusedtoassigninitialvalues​​totheloopvariablesbeforetheloopstarts.

Expression2isaloopcontrollogicexpression,whichcontrolstheconditionofloopexecutionanddeterminesthenumberofloops.

Expression3modifiestheexpressionfortheloopcontrolvariable,whichmakestheforlooptendtoend.

Theloopbodystatementisastatementthatisexecutedrepeatedlywhentheloopcontrolconditionissatisfied.

Butintheentireforloopprocess,expression1isonlycalculatedonce,expression2andexpression3maybecalculatedmultipletimes,ormaynotbecalculatedonce.Thebodyoftheloopmaybeexecutedmultipletimes,oritmaynotbeexecutedonce.

Първо изпълнете израз 2, след това изпълнете структурата на цикъла и накрая израз 3 и продължете да изпълнявате цикъла по този начин.

TheforloopstatementisthemostpowerfulstatementintheClanguage,anditcanevenreplaceotherloopstatementstoacertainextent.

направи

doloopstructure,do1while(2);редът за изпълнение е1->2->1...цикъл,2еусловието за цикъл.

докато

whileloop структура, редът на изпълнение наwhile(1)2;е1->2->1...цикъл,1istheloopусловие

Горният израз за цикъл, когато изразът на условието за цикъл е верен, цикълът ще продължи и ако е фалшив, той ще излезе от цикъла.

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.

ANSIC предоставя стандартни функции на библиотеката на езика.

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.

Приоритетът на операторите от горната част е приблизително: унарни оператори, аритметични оператори, релационни оператори, логически оператори, условни оператори, оператори за присвояване (=) и оператори запетая.

Разработване на програмиране

Компилатор

GCC, с отворен код и безплатен компилатор, разработен от организацията GNU

MinGW, под операционната система Windows GCC

Clang, компилаторът с отворен код, базиран на протокол BSD и LLVM

VisualC++::cl.exe, компилаторът, който идва с MicrosoftVC++

интеграцияСреда за разработка

Код::Блокове,отворен кодисвободен C/C++IDE

CodeLite,отворен код,междуплатформена C/C++интегрирана среда за разработка

Dev-C++, portableC/C++IDE

С-без

LightTable

VisualStudioseries

Примерна програма

Следното е проста програма, която отпечатва низа "Hello, world!" на стандартното изходно устройство (stdout). Подобна програма обикновено се използва като първата програма, когато изучавате език за програмиране:

#includeintmain(){printf("Hello,World!\n");return0;}
  1. Първият ред на програмата#include е директива за препроцесор, указваща на Cкомпилатора да включи най-новия файлdio.h преди действителната компилация.c език

  2. Следващият ред inintmain()е основната функция и програмата се изпълнява оттук.

  3. Следващият ред printf(...)е друга налична функция в C, която ще покаже съобщението "Здравей, свят!" на екрана.

  4. Следващият ред връща0;Прекратява функциятаmain()и връщастойността0.

#includeintmain{voidmove(int*xa,int*xb);inta,b;printf("Моля, въведете две цифри,b:");scanf("%d,%d",& ;a,&b);преместване(&a,&b);printf("a=%d,b=%d\n",a,b);return0;}voidmove(int*xa,int *xb){inta;a=*xa;*xa=*xb;*xb=a;}

1.Третият ред е декларацията на функцията, която декларира функция без връщана стойност с два параметъра на указателя. Тъй като дефиницията на функцията е под извикващата функция, тя трябва да бъде декларирана.

2.Четвъртият ред е дефиницията на променливи, която дефинира най-две променливи с цяло число.

3.Въведете две числа на шестия ред, които трябва да бъдат въведени със запетая, подобна на 1,0.Въведете две числа в променлива и b."&"е оператор на шапка.

4.Този седми ред извиква функциятапреместване за преобразуване на стойностите​​надвете променливи.

5.След основната функция следва дефиницията на функцията за преместване.

Ascanbeseenfromthisexample,pointervariablescangetmorereturnvalues,whichisveryconvenient.

This article is from the network, does not represent the position of this station. Please indicate the origin of reprint
TOP