Sie sind auf Seite 1von 25

1.

1Structureofaprogram
BYALEXO NMAY30T H,2007| LAST MO DIF IEDBYALEXO NNO VEMBER20T H,2016

Acomputerprogramisasequenceofinstructionsthattellthecomputerwhattodo.

Statements

Themostcommontypeofinstructioninaprogramisthestatement.AstatementinC++isthesmallestindependentunitinthe
language.Inhumanlanguage,itisanalogoustoasentence.Wewritesentencesinordertoconveyanidea.InC++,wewrite
statementsinordertoconveytothecompilerthatwewanttoperformatask.StatementsinC++areterminatedbya
semicolon.

TherearemanydifferentkindsofstatementsinC++.Thefollowingaresomeofthemostcommontypesofsimplestatements:

1 int x;
2 x = 5;
3 std::cout << x;

intxisadeclarationstatement.Thisparticulardeclarationstatementtellsthecompilerthatxisavariablethatholdsan
integer(int)value.Inprogramming,avariableprovidesanameforaregionofmemorythatcanholdavaluethatcanvary.All
variablesinaprogrammustbedeclaredbeforetheyareused.Wewilltalkmoreaboutvariablesshortly.

x=5isanassignmentstatement.Itassignsavalue(5)toavariable(x).

std::cout<<xisanoutputstatement.Itoutputsthevalueofx(whichwesetto5inthepreviousstatement)tothe
screen.

Expressions

Thecompilerisalsocapableofresolvingexpressions.Anexpressionisamathematicalentitythatevaluatestoavalue.For
example,inmath,theexpression2+3evaluatestothevalue5.Expressionscaninvolvevalues(suchas2),variables(suchas
x),operators(suchas+)andfunctions(whichreturnanoutputvaluebasedonsomeinputvalue).Theycanbesingular(suchas
2,orx),orcompound(suchas2+3,2+x,x+y,or(2+x)*(y3)).

Forexample,thestatementx=2+3isavalidassignmentstatement.Theexpression2+3evaluatestothevalueof5.
Thisvalueof5isthenassignedtox.

Functions

InC++,statementsaretypicallygroupedintounitscalledfunctions.Afunctionisacollectionofstatementsthatexecutes
sequentially.EveryC++programmustcontainaspecialfunctioncalledmain.WhentheC++programisrun,executionstarts
withthefirststatementinsideoffunctionmain.Functionsaretypicallywrittentodoaveryspecificjob.Forexample,afunction
namedmaxmightcontainstatementsthatfiguresoutwhichoftwonumbersislarger.AfunctionnamedcalculateGrademight
calculateastudentsgrade.Wewilltalkmoreaboutfunctionslater.

Helpfulhint:Itsagoodideatohaveyourmain()functionliveina.cppfilenamedeithermain.cpp,orwiththesamenameas
yourproject.Forexample,ifyouarewritingaChessgame,putyourmain()functioninchess.cpp.

LibrariesandtheC++StandardLibrary

Alibraryisacollectionofprecompiledcode(e.g.functions)thathasbeenpackagedupforreuseinmanydifferentprograms.
Librariesprovideacommonwaytoextendwhatyourprogramscando.Forexample,ifyouwerewritingagame,youdprobably
wanttoincludeasoundlibraryandagraphicslibrary.

TheC++corelanguageisactuallyverysmallandminimalistic(andyoulllearnmostofitinthesetutorials).However,C++also
comeswithalibrarycalledtheC++standardlibrarythatprovidesadditionalfunctionalityforyouruse.TheC++standard
libraryisdividedintoareas(sometimesalsocalledlibraries,eventhoughtheyrejustpartsofthestandardlibrary),eachofwhich
focusonprovidingaspecifictypeoffunctionality.OneofthemostcommonlyusedpartsoftheC++standardlibraryisthe
iostreamlibrary,whichcontainsfunctionalityforwritingtothescreenandgettinginputfromaconsoleuser.

Takingalookatasampleprogram
Nowthatyouhaveabriefunderstandingofwhatstatements,functions,andlibrariesare,letslookatasimplehelloworld
program:

1 #include <iostream>
2
3 int main()
4 {
5 std::cout << "Hello world!";
6 return 0;
7 }

Line1isaspecialtypeofstatementcalledapreprocessordirective.Preprocessordirectivestellthecompilertoperforma
specialtask.Inthiscase,wearetellingthecompilerthatwewouldliketoaddthecontentsoftheiostreamheadertoour
program.Theiostreamheaderallowsustoaccessfunctionalityfromtheiostreamlibrary,whichwillallowustowritetothe
screen.

Line2isblank,andisignoredbythecompiler.

Line3declaresthemain()function,whichasyoulearnedabove,ismandatory.Everyprogrammusthaveamain()function.

Lines4and7tellthecompilerwhichlinesarepartofthemainfunction.Everythingbetweentheopeningcurlybraceonline4
andtheclosingcurlybraceonline7isconsideredpartofthemain()function.

Line5isourfirststatement(youcantellitsastatementbecauseitendswithasemicolon),anditisanoutputstatement.
std::coutisaspecialobjectthatrepresentstheconsole/screen.The<<symbolisanoperator(muchlike+isanoperator)called
theoutputoperator.std::coutunderstandsthatanythingsenttoitviatheoutputoperatorshouldbeprintedonthescreen.In
thiscase,weresendingitthetextHelloworld!.

Line6isanewtypeofstatement,calledareturnstatement.Whenanexecutableprogramfinishesrunning,themain()function
sendsavaluebacktotheoperatingsystemthatindicateswhetheritwasrunsuccessfullyornot.

Thisparticularreturnstatementreturnsthevalueof0totheoperatingsystem,whichmeanseverythingwentokay!.Nonzero
numbersaretypicallyusedtoindicatethatsomethingwentwrong,andtheprogramhadtoabort.Wewilldiscussreturn
statementsinmoredetailwhenwediscussfunctions.

Alloftheprogramswewritewillfollowthistemplate,oravariationonit.Wewilldiscusseachofthelinesaboveinmoredetail
intheupcomingsections.

Syntaxandsyntaxerrors

InEnglish,sentencesareconstructedaccordingtospecificgrammaticalrulesthatyouprobablylearnedinEnglishclassin
school.Forexample,normalsentencesendinaperiod.Therulesthatgovernhowsentencesareconstructedinalanguageis
calledsyntax.Ifyouforgettheperiodandruntwosentencestogether,thisisaviolationoftheEnglishlanguagesyntax.

C++hasasyntaxtoo:rulesabouthowyourprogramsmustbeconstructedinordertobeconsideredvalid.Whenyoucompile
yourprogram,thecompilerisresponsibleformakingsureyourprogramfollowsthebasicsyntaxoftheC++language.Ifyou
violatearule,thecompilerwillcomplainwhenyoutrytocompileyourprogram,andissueyouasyntaxerror.

Forexample,youlearnedabovethatstatementsmustendinasemicolon.

Letsseewhathappensifweomitthesemicoloninthefollowingprogram:

1 #include <iostream>
2
3 int main()
4 {
5 std::cout << "Hello world!"
6 return 0;
7 }

Visualstudioproducesthefollowingerror:

c:\users\apomeranz\documents\visualstudio2013\projects\test1\test1\test1.cpp(6):errorC2143:
Thisistellingyouthatyouhaveansyntaxerroronline6:Youveforgottenasemicolonbeforethereturn.Inthiscase,theerror
isactuallyattheendofline5.Often,thecompilerwillpinpointtheexactlinewherethesyntaxerroroccursforyou.However,
sometimesitdoesntnoticeuntilthenextline.

Syntaxerrorsarecommonwhenwritingaprogram.Fortunately,theyreofteneasilyfixable.Theprogramcanonlybefully
compiled(andexecuted)onceallsyntaxerrorsareresolved.

Quiz

Thefollowingquizismeanttoreinforceyourunderstandingofthematerialpresentedabove.

1)Whatisthedifferencebetweenastatementandanexpression?
2)Whatisthedifferencebetweenafunctionandalibrary?
3)WhatsymboldostatementsinC++endwith?
4)Whatisasyntaxerror?

QuizAnswers

Toseetheseanswers,selecttheareabelowwithyourmouse.

1)ShowSolution

2)ShowSolution

3)ShowSolution

4)ShowSolution

1.2Comments

Index

0.7AfewcommonC++problems

Sharethis:

Facebook Twitter Google Pinterest

C ++TU TOR IAL | PR IN TTH ISPOST

157commentsto1.1Structureofaprogram

Joyel
June27,2008at6:48pmReply

Thanksforthispartofthetutorial.Ifoundthissectionreallyhelpful.

pavuluri
January29,2015at2:30amReply

Thanksforthevalublepost,ItisveryusefulC++Programmingexamplesforbeginners

parasyte
October21,2008at10:08pmReply

heymanverynicethoughyouwrotewouldliketousetheiosteamlibrary.inthefirstparagraphafter
Takingalookatasampleprogram

Alex
October25,2008at9:55amReply

Imnotsurewhattheproblemiswiththat.AmImissingsomething?

sorry188
November13,2008at7:24amReply

iosteamshouldbeiostream.Itismissinganr.

[Wow,IcantbelieveIdidntseethat.Fixednow!Thanksall.Alex]

ghost
February10,2010at3:38amReply

usingnamespacestdisinthewrongline
itshouldbeinthemainheaderbeforeintmain()

Alex
January2,2015at2:49pmReply

No,itshouldnt.Ifitsinthemainfunction,thescopeofthestatementonlyappliestothe
function(whichisgood).Ifyouputitinthemainpartoftheprogram,itappliestotheentire
file,whichisgenerallyconsideredpoorform(andcouldleadtonamingcollisions).

Cole
April8,2015at1:46pmReply

Heyyourestillreadingcomments!Thatsawesome.Ijuststartednotthatlongago.
Thanksforputtingtheseup

Stormie
April8,2016at4:21pmReply

Metoo,anditissuperawesome!

Ganesh
June17,2016at5:36amReply

Alexiswrite

Alex
June20,2016at10:52amReply

Iwrite,thereforeIam.

Ganesh
June17,2016at5:46amReply
Ifyouuseiostreaminsteadofiostream.h,youshouldusethefollowingnamespacedirective
tomakethedefinitioniniostreamavailabletoyourprogram.usingnamespacestdatthe
beginningoftheprogramisbitlazyandpotentiallyaprobleminlargeprojects.thepreferred
approachesaretousethestd::qualifierortousesomethingcalledusingdeclarationtomake
justparticularnamesavailable.forexampleusingstd::cout.

Gilbert
February18,2010at11:26pmReply

ImnotsureifitdifferentiatesbetweenC++CompilersornotbutImusingVisualC++andmy
programwillnotcompileunlesstheusingnamespacestdisoutsideofthemainfunction

adam
December16,2008at4:47pmReply

isanexpressionatypeofstatement?

Alex
December22,2008at11:19pmReply

Imnotquitesurehowtoanswerthat.

Inmostcases,andexpressionisPARTofastatement.Forexample:

1 x = 2 + 3;

2+3isanexpressionthatevaluatesto5.x=2+3isanassignmentstatementthatassignstheresultof
evaluation2+3tovariablex.

Itispossibletohaveastatementthatconsistsonlyofanexpression.Forexample,thefollowingisallowed:

1 2 + 3;

Thisexpressionevaluatesto5,butsincetheresultisnotusedanywhereitisjustdiscarded.

adam
December18,2008at4:09pmReply

ifcout<<Helloworld!<<endlisastatementand<<isanoperatorwhatiscoutacommand?

Alex
December22,2008at11:21pmReply

coutisactuallyavariablethatispredefinedbythestandardlibrary.Thevariableisoftypeostream,
whichisaclass.Classesallowyoutodefineyourownvariabletypes.Wecoverclassesinmoredetail
inchapter8.

vivek
June18,2010at3:27amReply

ifcoutisanobjectofaclass,thenwhoactuallydoesinstantiateit?wedonotcreatethis
instanceinourcode.Isthisobjectcreatedbeforetheactualcodeisexecuted?

Alex
January2,2015at2:55pmReply

Greatquestion.Whenyouincludeiostream,theiostreamhasaninstatiationofcout.
zohaib
November25,2015at6:44amReply

lolyourepliedlike5yearslateronthatone

Alex
November25,2015at2:25pmReply

Betterlatethannever.

terrell
March11,2009at5:22amReply

IhaveVisualC++2005ExpressEdition,
butmylinesarentnumbered.Why?

Quinn
July10,2009at6:58pmReply

ThisarticlehassomehelpfulinformationforturningonlinenumberinginVisualStudio2005.

AndtoaddinalittleOpenSourceplug(IswearImnotbeingpaid),Code::Blocksturnsonlinenumberingbydefault.

TheLeadingMan
May11,2009at6:09amReply

skewyou

Noha
May14,2009at5:41amReply

IsthereanyexplanationaboutthestructureofStandardTemplateLibrary(STL)inthissite?

Ray
August2,2009at5:56pmReply

Wowurteachingortutorialhereismuchbetterthanmyteacher.Imcurrentlystudyingengineeringwithc++
asamodulebuttillnowinvrknewthetruemeaningof0atthereturn0.

vishvesh
August9,2009at7:48pmReply

Itwouldbegoodifyoucouldexplainthedifferencebetweenfunctionsandmethods.

Alex
January2,2015at5:47pmReply

Amethodandafunctionareessentiallythesamething.InC++,weusuallyusethetermfunctionwhen
thefunctionisindependentofanobject,andmethod(ormorecommonly,memberfunction)whenthe
functionispartofanobject/class.

venne
November21,2009at10:22amReply
1 Hi Alex,
2
3 Firstly I should thank you for such a great tutorial.This is one of the best sites I ever foun
4 d .
It really helped me a lot .

IsNe
December27,2009at5:16amReply

Whenicodeiplacethe:

1 using namespace std;

atthetop

1 #include <iostream>
2
3 using namespace std;
4
5 int main()
6 {
7 cout << "Hello world!" << endl;
8 return 0;
9 }<!--formatted-->

itstillworks,isntthatmoreconvinient?oristhereareasonforplacingitinsideeachandeveryfunction

Alex
January2,2015at5:50pmReply

Itsmoreconvenientperhaps,butalsomoredangerous.Ifyouputtheusingnamespacestdstatement
atthetopofyourcode,itappliestoeverythinginthefile.Thisincreasesthechanceofnaming
collisions.

Generally,itsbettertoeitherputtheusingstatementineachfunctionthatneedsit,orcallcoutdirectlyusingthe
scoperesolutionoperator(e.g.std::cout).

chris03653837
February14,2010at12:02pmReply

yougysneedtostopsmokingbadweed,thecodeisfine.

Met
March29,2010at4:02amReply

verygoodwebsitethis.thankstotheAdminofthiswebsiteandthepeoplewhomadethispossiabletous.
Greatlessons

thanksagain

Albanian.

Endrit
April5,2015at8:57amReply

HahahImAlbaniantoo
AndImtryingtolearnthislanguage
MadhuReddy
August8,2010at10:11amReply

Plzexplainusingnamesapacestdinmoreunderstandablemanneralexsir.

AdamSinclair
August15,2010at9:34pmReply

usingnamespacestdisbasicallyusing"std"throughouttheentirecode.

Insteadofwritingstd::cout::<<"HelloWorld!"<<std::endlorsomethinglike
that.Youwon'thavetoincludeallthat"std::"ifyouhave

usingnamespacestd

hawk1821
December11,2010at8:50amReply

Goodstuff!!!

cubbi
April12,2011at5:41amReply

Endlisaspecialsymbolthatmovesthecursortothenextline
Thisisincorrect.Thespecialsymbolthatmovesthecursortothenextlineis\n.Abuseofstd::endlforthis
purposeisbadpracticewhichleadstoinefficientprograms.

sh@kil
August20,2013at5:44amReply

thanks

Alex
January2,2015at6:39pmReply

Iupdatedthewordingtobemoreprecise:

Endlisanotherspecialobjectthat,whenusedinconjunctionwithcout,causesthecursortomovetothenextline
(andensuresthatanythingthatprecedesitisprintedonthescreenimmediately).

Youarecorrectthatoveruseofstd::endlcancauseperformanceissuesincaseswhereflushingthebufferhasa
performancecost,suchaswhenwritingtodisk.Imadenotesofthisinlesson13.6BasicFileI/O,whereItalk
aboutbufferingandflushinginmoredetail.

Homesweetrichard
May15,2011at8:41amReply

Onmac(xcode)therewillbeoneerrorifyoufollowitexactlyasshownonthispage.Insteadusethisone

#include

intmain(){
usingnamespacestd
cout<<"Helloworld!"<<endl
return0

Evenifyouhaveignorewhitespaceonitwillstillerr.Sodonotgive"{"itsownlinethatsbadprogrammingonxcode.ittook
meaweektofigurethatout,becauseiwaswonderingwhyitwasnt"build&run"soistartedtoplayaroundwithspacing,
afterihadalreadyasked10differentsiteswhydidntthiscodework,turnsoutitdoes,justrequiresacertainspacing
requirement.Myguessisyoucantuse"{}"withouttellingitwhyitsthere.thatsprobablyabadexplainationorwrong
explaination.

zingmars
May20,2011at9:02amReply

Oryourcompiler/IDEsucks.AnystandardC++compilerwhichfollowsthespecificationsshouldbe
abletocompilewithallthewhitespaceyouneed.

wesley_fung2
June12,2011at1:07pmReply

ohhheveryniceiunderstand!
thanks!learncpp.com

betefeel
June29,2011at9:40pmReply

Istarteddoingsomethingsonmyownhehehe

#include

intmain()
{

intx
inty
intd
intf
x=5
y=5
d=x+y
f=d+d

usingnamespacestd
cout<<x+y<<endl
cout<<f<<endl
return0

pmc24
October9,2011at12:20pmReply

Consistencyissue.

Forbeginners,themovefrom

usingnamespacestd

to

std::

mightbeconfusing.

HenceIsuggestamendingtheexamplecodeaccordingly,orleavinganoteattheendofthetutorialhighlightingthe
interchangeabilityfeatureofthetwo.

Alex
January2,2015at7:37pmReply

Iaddedasidenoteaboutthis.Hopefullyitisntinformationoverloadatthispoint.
ballooneh
March13,2012at3:48pmReply

Heythere!

Iamwonderingwhatintdoesinintmain().
Whatdoesitdoandwhendoiuseit?

Ialsoreadsomewherethatyoucanusevoidinsteadofint.
Whatdoesvoidmeanandwhatdoesitdo?

Alex
January2,2015at7:40pmReply

Italkaboutallofthesethingsinsection1.4Afirstlookatfunctions.Ifyoukeepfollowingthe
tutorials,youllgetthereshortly.

plusminus
May16,2014at8:35amReply

Whyweneedoperators?

Alex
January2,2015at7:52pmReply

Operatorsprovideaconvenientandconcisewayforustogetdifferentthingstointeract.

Takeforexample3+4.The+operatoradds3and4toproducetheresult7.

Withcout<<"Helloworld",the<<operatortakes"Helloworld"andgivesittocouttoprintonthescreen.Without
the<<operator,thecompilerwouldn'tknowwhether"Helloworld"wasmeanttointeractwithcoutorsomethingelse.

moddathier
August8,2014at4:15amReply

thanksforeveryonewhodothissitethanxmuch

Ali1
December3,2014at12:00pmReply

Thanksforthissiteowners

JosephH
January21,2015at6:48amReply

Ijuststartedwiththetutorialyesterdayandcompletedmyfirstprogram!IaminHSandwanttolearnc++
becauseIwanttobeacomputerprogrammer!Thankyouthisisallgoodandifyouhaveanytipsformeor
othercodesIcanlearnonlinepleasecomment!!!

Maria
January31,2015at2:43amReply

veryniceworking..

Sind
February3,2015at9:21amReply
intx
Thistellsthecompilerthatxisavariable

Doesthismean,memoryisallocatedforvariablexwhenvariablexisdeclared?
Whatexactlyisthedifferencebetweendeclarationanddefinition?

Alex
February3,2015at9:59amReply

Reallygoodquestionaboutthedifferencebetweendeclarationanddefinition.Theeasiestwaytothink
aboutitisasfollows:

*Adeclarationintroducesanobjectobject(function,variable,etc)anditstype.Afunctionprototypeisanexample
ofadeclaration.Adeclarationisenoughtosatisfythecompiler.Youcanhavemultipledeclarationsforthesame
object.

*Adefinitionactuallydefinesthatobject.Afunctionwithabodyisanexampleofadefinition.Adefinitionisneeded
tosatisfythelinker.Therecanonlybeonedefinitionforanobject.

Inmanycases,asinglelineservesasboththedeclarationanddefinition.Forexample,intxisadeclarationANDa
definition.

Memoryisallocatedatthepointofinstantiation,whichiswhentheobject(variable)isactuallycreated.Thispoint
canvarydependingonwherethevariableis.Forexample,ifavariablelivesinsideafunction,thevariablewontbe
created(andmemoryassigned)untilthatfunctionexecutes.

JohnZulauf
June17,2016at7:37amReply

First,rememberthatthedeclarationispurelysemantic.Youhaveanamethatlogicallyassociates
withatypeandavalue.Whatthecompilerdoeswillvary.Seethesectiononbuildconfigurations
above.

For"debug"builds,variableslocaltoafunctionaretypicallygivenmemorywhenfirstassignedavalue.That
memoryisonlypresentforaslongasthevariableisinscope(i.e.codeisexecutingwithinthe{}thevariable
wasdefinedin,andthenissubjecttoreuse.

Forreleasebuilds,typicallythecompliersoptimizerisenabledandallbetsareoff.Localvariables(thosethat
arepartofafunction)arenotguaranteedtohave*any*memoryisallocated.Dependingonhowxisused,x
mayonlyeverexistinsideaCPUregisterandneverbestoredtomemory.Otheroptimizationsmightcollapse
alllogicaloperationsonxtoalogicallyequivalentsetofinstructionsthatdonteverhaveanyofthevaluesthat
xwouldlogicallytakeon.

Debuggingreleasebuildscanbeaseriouspain,andbugsthatonlyexistinreleasebuildsareamongthemost
pernicious.

Amir
February14,2015at11:41pmReply

Hello.IamFromIranandinmyUniversityILearnedthePythonverywell.butdontteachthec++.
thisSiteisverySpecialandverygood.
thanksforallyourdifficulty.

Xola
February19,2015at12:12pmReply

HihowcanIgttheminGwcompiler,currentlymusingturboC++
It'squitetrickytoworkwith.

AkshitS
March1,2015at5:15amReply
Soafterexecutionofourprogram,compilerreturnsavaluetotheOSindicatingwhetherornotourprogram
wassuccessfullycompiledandexecuted.But,herewearealreadyspecifyingareturnvalue(intheabove
case,'0').WeforcefullywantourcompilertotellourOSthattherewasn'tanyerrorinourprogram.Shouldn't
thisjobbehandledbycompileritself,insteadofuserspecifyingareturnvalue?

Alex
March1,2015at6:23pmReply

Attheendofexecutionofourprogram,theprogramreturnsavaluetotheOS(notthecompiler).

Typically,thingshappeninthisorder:
*Programmerwritescode.
*Programmerusescompilertocompilecodeintoanexecutable.(Thecompilersjobisdoneatthispoint)
*Userrunsexecutable.
*ExecutablereturnsacodetotheOStoindicatewhethertheexecutableransuccessfully.

Thecompilergenerallywontevenberunningwhentheexecutableisrunning(unlessyouredebugging).

PankajJain
March1,2015at3:08pmReply

HiAlex,

Quotingfromthepage:
"Line1isaspecialtypeofstatementcalledapreprocessordirective.Preprocessordirectivestellthecompilertoperforma
specialtask.Inthiscase,wearetellingthecompilerthatwewouldliketousetheiostreamlibrary.Theiostreamlibrarywill
allowustowritetothescreen."

Inmyopinion,includedirectiveisusedtoaddtheheaderfilesandnotanylibrary.Itisusedfordeclarationoffunction
prototypetobeusedincppfilesothatcompilerdoesnotgiveundeclaredidentifier/missingdeclarationerror.

Pleasefeelfreetocorrectmeifmyunderstandingiswrong

Regards,
Pankaj

Alex
March1,2015at6:43pmReply

Iveclarifiedthewordingabit.#includingtheheaderaddsthecontentsoftheiostreamheadertoour
program.Thisprovidesourprogramwithfunctionality(aninterface)toaccessthecontentofthe
iostreampartofthestandardlibrary.

PankajJain
March2,2015at4:53amReply

ThankyoufortheclarificationAlex.Ifindthesetutorialsreallygoodtobrushupmybasics.I
reallyappreciatealltheeffortthathasbeenputtomakethesetutorials

TKM
March9,2015at7:51pmReply

AnExcitingTutorialHopetocontinue

Batuhan
April2,2015at3:18amReply

std::cout<<"verygoodtutorial"
kausthub
April13,2015at5:26amReply

Iwanttoknowwhenyoulastupdatedthelessonswiththe"Updated"symbol.Ihavealreadylearntalotof
lessonssoIdontknowifyouupdatedafterIlearnt.

PankajKushwaha
April13,2015at11:58pmReply

ThanksalotAlex,forawonderfulandfreetutorial.

richardharris
April26,2015at6:04amReply

Comingbacktoc(c++)afteryearsofscriptinginPHP/JavaScriptetc.Firstlearneditin1991anditseems
likeonlyyesterday.However,thetoolshavechangeddramaticallysothistutorialisagreatguidethanyou.

kobby
May10,2015at9:46amReply

Ineverdreamtofstartingthec++programming,ialwaysturnmyselfdown.Butlikeadream,iambeginningto
understandAlexstutorials.Tnxforsharingyourknowledge,Alex.

Odgarig
May17,2015at9:03amReply

Imreallyenjoyinglearningc++fromyou.Thankyou.

Niranjan.A.S
May17,2015at10:19pmReply

Thanks

Colleen
May21,2015at9:54amReply

ThankyouAlex.IamlookingforacareercbangeandthisisexactlywhatIneedforit.

vikashverma
June14,2015at12:52amReply

veryhelpful.thanks

Ivxcfvrt
June14,2015at7:23amReply

AnexpressionisAmathematicalentity

Alex
June15,2015at1:02pmReply

Itsureis.Typofixed.

newprogrammer
June19,2015at3:45pmReply
oddquestionbutdopreprocessordirectivesalwaysneedtobeinthefirstlinesofthefile?whatifiwantedto
includealibraryonlyforaspecificfunctioninsteadofthewholeprogram?

Alex
June20,2015at8:05pmReply

Preprocessordirectivescanbeusedanywherewithinafile.However,byconvention,#include
directivesaregenerallyusedatthetopofafilesoitseasytoseewhatsbeingincluded.

Iveneverseensomeone#includeafileforaspecificfunctionbefore,thoughIsupposeitwouldbepossible.

techdummy
June25,2015at10:48pmReply

MRALEXidontknowanythingatallandiamadummyinthisfield.Doineedtoknowanythingbeforehandto
getstartedintotheworldofprogramming.

Alex
June26,2015at9:11amReply

Followthetutorialsinorderandtheyllteachyoueverythingyouneedtoknowtocompletethem.

ParthPatel
July4,2015at6:12pmReply

Thanksforthisawesomepost

R4Z3R
July10,2015at4:45amReply

Whatisthedifferencebetweenheaderandlibrary!?

Alex
July12,2015at10:00amReply

Aheaderfileisafilethattypicallycontainsdeclarationsmeanttobeusedbyotherfiles.Onceyour
programsgettothepointwheretheyremorethanonefile,headerfilesbecomequitecommon.

Alibraryistypicallyacollectionofreusableheaderfilesandprecompiledcode.Inordertousethelibrary,you
#includetheheaderfilesinyourcodeandlinkintheprecompiledcode.

Icoverheaderfilesinlesson1.9HeaderfilesandlibrariesinappendixA.

ADDas
July20,2015at9:05pmReply

heyman..theseareallusingvisualc++butinourschoolweuseturboC++wherethesyntaxismuch
different..isthereanywherewhereicanlearnusingturboC++??

Alex
July21,2015at9:37amReply

MostofwhatistaughtinthesetutorialsshouldstillworkinTurboC++,excludingnewerC++features
(e.g.C++11stuff)andparticularfeaturestheyneverimplementedfullsupportfor.
Dyl@n
July27,2015at6:31amReply

Thankyouformakingthissoeasytounderstand,myonlyquestionisthatafterIfinishthiswholethingshould
Ibeabletowritecandc++withoutaproblem?Ijustdontwanttospendallthistimeandhavethelessons
grazeoverimportantthingslateron.

AlyKhairy
August13,2015at10:08pmReply

WhenIpasted
#include<iostream>

intmain()
{
std::cout<<"Helloworld!"
return0
}

thecoutandmainwerentcoloured.

Thecodewouldntrunandgavemeanerror.

Alex
August14,2015at1:23pmReply

SoundslikemaybeyourprojectisntsetupasaC++project.Gobacktotheinitiallessonsandmake
sureyouvesetyourprojectuptherightway.

AlyKhairy
August14,2015at9:36pmReply

Thefilesendwith.cpp

AlyKhairy
August16,2015at1:18amReply

Pleasereply

Alex
August16,2015at4:59pmReply

AreyousureyoureusingVisualStudioandnotsomeotherprogram(likeVisualStudio
Blend?)
AreyousureyourprojectisaC++win32consoleapplication?

AlyKhairy
August16,2015at11:14pmReply

IusedthelinkprovidedandgotVisualStudio2015.Ialsofollowedtheinstructionsto
theletter.IncaseIdidmisssomething,howwouldIcheck?

Alex
August17,2015at12:00pmReply
UsethefeedbackformintheContactsectiontocontactme,andletstakethisdiscussionto
email.Itsgoingtorequiresomediagnosisandgoingbackandforthwhichismoreappropriate
foranemaildiscussionthanhere.

george
August25,2015at6:32amReply

Whatdoesarbitraryvaluemean?

Alex
August25,2015at12:10pmReply

Byarbitraryvalue,Ireallymeantavaluethatislefttotheprogrammerschoice.

Irewrotethedefinitiontomakeitclearer:

Variablesservethesamepurposehere:toprovideanameforavaluethatcanvary.

Ithinkthatcapturestheintentslightlybetter.

george
August28,2015at5:09amReply

Thanksthatclearsitup

P.s.Ilovethetutorial

Stian
August29,2015at2:50amReply

Foundthatyouneedtodeclareafunctionjustlikeavariablebeforeitcanbeused.Sothisforexamplewillnot
work:

1 #include "stdafx.h"
2 #include <iostream>
3
4 int main()
5 {
6 std::cout << "start" << std::endl;
7 test();
8 std::cout << "end" << std::endl;
9 return 0;
10 }
11
12 void test() {
13 std::cout << "function response" << std::endl;
14 }

Howeverifyoumovethetest()functiontobeforethemainlikethis:

1 #include "stdafx.h"
2 #include <iostream>
3
4 void test() {
5 std::cout << "function response" << std::endl;
6 }
7
8 int main()
9 {
10 std::cout << "start" << std::endl;
11 test();
12 std::cout << "end" << std::endl;
13 return 0;
14 }
Itwill.
JustfeltifworthnotingasImusedtoJSatthispointandfunctionscanbecalledfromaanypointinthefilebeforeorafter
its"declared",andthereareprobablymoreinthatsamesituation.
Igotstuckforalittleminutetherejustthoughthatsomeonemighthavemoretroublefindingthesolution.

Alex
August31,2015at4:09pmReply

Yup!Wetalkaboutthisinmorelengthinupcominglessons.

Goku
September15,2015at7:48amReply

Greatexplanation,havingasmallquizattheendwasveryhelpful,thanks

bolkay
October1,2015at12:16amReply

Whao,Ilovethis!!!!@!@Reallywanttolearnthis.

sorceror
October23,2015at7:58amReply

ilikethistoprogrammymagicspells,hahhahahehehe

Nyap
October25,2015at11:34amReply

Hey,
Im12yearsoldandIminterestedinlearninghowtocodeC++.
Itestedmyselfonthissection.IfanyonehasthetimetocheckifIgoteverythingright,thenplzdoso.

http://www.heypasteit.com/clip/28UL

IfIdiddosomethingwrong,thenpleaseexplainwhatthecorrectanswerisinthesimplestbutmostinformativeway
possible.Thanks.

Sagar
October30,2015at9:58amReply

myteachertaughtmeas:#include<iostream.h>
for:#include<iostream>
andlittlebitdifferentfromurhelloprogram,
isthisadifferentmethod?ifso,howdoIchangeurcodewiththatmyteachertaughtforbetterunderstandingofc++.
Thanks!ursiteisagreathelp..

Hesam
December27,2015at12:50pmReply

Hello
Thisismyfirsttimeoflearningcpp,everythingwasok.withoutanyhelpfromanybody,justthroughyour
website,Ilearnedtoknowaboutvisualstudio,howtoinstallitandhowtostartyourfirstlesson.ThankyouverymuchIam
sohappyaboutthat.

Nand
January9,2016at2:50amReply

DearAlex,
Itissowellexplained..GodBlessyou..

Thanks!ursiteisagreathelp..

Harini.D
January18,2016at12:40amReply

Whyshouldntweuse

#include<iostream.h>
Insteadofusing
#include<iostream>
Isthatright?

Alex
January19,2016at2:08pmReply

No,iostream.hisoutdated.Italkmoreaboutthisinafewlessons.

L.a.Inspire
January19,2016at8:30amReply

Thankyouverymuch!Alex.

Thai
February5,2016at7:17pmReply

thankyou!

MalReddy
February15,2016at10:25pmReply

actuallyiambeginner,whataretheobjectandclassinc++.

Alex
February16,2016at10:09amReply

Anobjectisjustanothernameforaninstantiatedvariable.Inobjectorientedprogramming,anobjectis
oftenusedtorefertoaninstanceofaclass.

Aclassisauserdefinedtypethatbundlesdataandfunctionsthatworkonthatdatatogether.Wediscussclassesin
chapter8onward.

DanL
February16,2016at2:19pmReply

ThislessonstatesthatC++variablesarethesameasalgebravariables.Insteaditshouldcontainawarning,
somethinglike:YO,C++VARIABLESARENOTTHESAMEASALGEBRAVARIABLES!!Becausetheyre
not,andthinkingthattheyarecanreallymesswithanewprogrammer.Algebravariablesdontactuallyvary,theyare
constant,thusitmakessenseto"solveforX."YoucanthinkofC++variableslikeholders,orcontainers.Likeacoffeecup
isacontainerforcoffee,"intx"makes"x"acontainerforaninteger,butnotaparticularinteger,itcancontainANYinteger,
anditcanchangefrommomenttomoment.Ipeekat"x"rightnowanditcontains"7",butIchecklateranditholds
"1533".Nowifyouuse"x"asanintegerinyourprogram,youcontrolititdoesntjustrandomlychangevalue.Realize
that,althoughImusing"x"asanintegerhere,itcouldcontainalmostanything,likewords,sentences,alistofalltheUS
presidents,evenC++code,andthisisoneofthewaysthatC++canbeveryconfusingtoreadandwrite.Thatdoesnot
meanthatyoucanplugaquadraticequationintoaC++expressionandexpect"x"toequalthesetofsolutions.Variablesin
algebraandinprogramsarethingsthatstandinforotherthings,buttheyaremaybemoredifferentthantheyarethesame.
Alex
February17,2016at1:27pmReply

Iwastryingtodrawananalogybetweentheconceptofusinganametorepresentavalue.However,I
canseehowthismightbeconfusingforpeoplewhothinkthatvariablesinprogrammingareidenticalto
variablesinalgebra.Asyourightlypointout,theyarent.Iveremovedthereference.

Nyap
February17,2016at7:00amReply

Hey,Imsortofconfusedaboutlibraries.
a)Soyoucanhavelibrariesinsideoflibraries?(iostreamlibraryinsidec++standardlibrary?)
b)Insection0.4,whenyouweretalkingaboutlinking,youmentioned"theruntimesupportlibrary".Isthisjustanothername
fortheC++StandardLibrary?

Nyap
February17,2016at7:31amReply

also,notreallytodowithlibraries,butwhenthecompilercreatesobjectfiles,isitbasicallyconverting
allyourC++codetobinarycode?Ifthatmakessense?

Alex
February18,2016at5:28pmReply

Yes.Objectfilesaremostlybinarycode,butalsosomeadditionalinformationrequiredtolink
multipleobjectfilestogetherintoafinalexecutable.

Alex
February18,2016at5:25pmReply

a)No,whenpeopletalkabouttheiostreamlibrarytheyrereallytalkingabouttheiostream
functionalityinsidetheC++standardlibrary.
b)TheruntimesupportlibraryisthesamethingastheC++standardlibrary.Illupdatethelanguageinlesson0.4.

Frank
March15,2016at1:23amReply

HeyAlex,wherecanIgetthelistofcodesandthiercorrespondingfunctions.

Alex
March17,2016at2:24pmReply

Whatdoyoumeanbycodes?

Stormie
April8,2016at4:41pmReply

Ithinkhemeansthetextsuchas"std","int"&"cout".Ihavebeenfollowingthetutorial(whichis
veryhelpful)andoneofthefirstthingsIthoughtofneedingisareferencecardorglossaryof
abbreviations.Wouldthisbeuseful?Orisitmuchmorecomplicatedthanthatandthesame"code"(notsure
whatthetermwouldbe)changesdependentontheinstanceitisusedin?
NiceoneAlexforthesetutorialsand(continuing!)respondingtocomments.Ilearnedalmostasmuchfromthe
commentsasfromthetutorialiehownottodothingsorwhysomepeoplemaydothingsdifferentlyandan
initialunderstandingofwhattheprosandconsmightbe.
Alex
April9,2016at11:19amReply

Ifyourethetypeofpersonwholikestowritenoteswhilelearningsoyoucanreferenceback
tothingsyouvealreadylearned,thenbyallmeans,yes,createalistasyoulearn.

AtsomepointImaycreateaglossary,butitdoesntexistcurrently.

IshwarSingh
April25,2016at9:40pmReply

ItssohelpfulThankstouAlex

Benedikt
May24,2016at10:02amReply

#include<iostream>
usingnamespacestd

voidcout()
{
//
}

intmain()
{
std::cout<<"HelloWorld">>
system("PAUSE")
}

Iworkwithacleanmapandmoustcreatemyownmain.cpp
andItworksnormalywiththisCodebutIgotaerrorandIdontknowwhyitdoesntworkcanyouhelpme?

Alex
May24,2016at12:16pmReply

Twoquestions:
1)Whaterrordidyouget?
2)Didyoucreateaproject/solutionforthiscode,orjusta.cppfileoutsideofaproject?

Benedikt
May24,2016at11:51amReply

Ijustcantfindthegooddammmisstake,IknowitsahardwaytogoodcreateacalculatorbutItrysomenew
thingslikeifandelseifitwasneededicanwritethesamestuffonenglish,plshelpme

#include<iostream>
usingnamespacestd

intmain()
{
{
intzahl1
intzahl2

cout<<"BitteeinebeliebiegeZahleingeben!"<<endl
cin>>zahl1
cout<<"DankeSiehaben"<<zahl1<<"eingegeben"<<endl
cout<<"Gebensienun"<<zahl2<<"ein"<<endl
cin>>zahl2
cout<<"Dankesiehaben"<<zahl2<<"eingegeben"<<endl

cout<<"wollensiemitdenZahlen1und2Rechnen?"<<endl

charantwort=

cout<<"Ja(j)/Nein(n):"
cin>>antwort

if(antwort==j)
cout<<"Duhastjagewhlt"<<endl
cout<<"waehlensienunihrRechenzeichen"<<endl
cout<<"+,,*,/"<<endl
if(cin>>"+")
cout<<"zahl1+zahl2"<<endl
else(cin>>"")
cout<<"zahl1zahl2"<<endl
if(cin>>"!=+,")

charantwort=

cout<<"(*),(/):"
if(cin>>("*"))
cout<<"zahl1*zahl2"<<endl
else(cin>>("/"))
cout<<"zahl1/zahl2"<<endl

return0

Alex
May24,2016at12:21pmReply

Itlooksliketherearequiteafewmistakesinthere.Insteadofdebuggingthis,Idliketosuggestyou
readabitfurtherinthetutorialseriesandthencomebacktothisprogramagain.

Benedikt
May26,2016at6:48amReply

thanksfortheanswer,andIjusttrysomenewthingsbecauseiwouldtrysomething,soireadmoreand
wouldtryitagain

ODHIAMBO
June10,2016at5:41amReply

excellent

BeaverFeaver
June28,2016at4:14amReply

ThiswasreallyhelpfulAlex,thanks:).

Sahal
July14,2016at1:26pmReply

WhatisthedifferencebetweenDEBUGGINGandCORRECTINGSYNTAXERRORS???
PratikPanda
July15,2016at9:31pmReply

Isresolvingofanexpressionperformedatcompiletime?Oritisperformedatruntimealso.
Iamthinkingofthesesituationsaspermyexamplesbelow

Compiletime

1 x = 2 + 3;

Runtime

1 x = a + b;

Note:Valueofaandbaretakenfromconsoleatruntime.
PleasecorrectmeifIamwrong.

Alex
July18,2016at4:38pmReply

Yes,someexpressionscanberesolvedatcompiletime.Thesearecalledconstantexpressions.Italk
amoreaboutthisinchapter2.

Raul
July16,2016at12:10amReply

WOW,amazingwebsite.ImnewtoC++andImreallytakingmytimereadingeachchapterandtheviewers
comments.IinstalledVisualStudio2015andCode::BlocksandIlikethelaterbetter.Imrunningbothatthe
sametimetoseethedifferences.VisualStudio2015takesalittlelongertocompilethanCode::Blocks.SofarIhavenotrun
intoanyissue,butImlikingCode::Blocksbetter.ImhopingallchaptershaveCode::BlocksexamplesifIrunintoanissue

IrememberusingVisualBasicbackincollegein2000,hadtotakeitbecauseofmymajor.IalsousedTinyCCompiler,
HTMLKitandsomeotherfreewareprogramsatthattime,butIcantellthingshavechanged,haha.

Greattohaveaquizattheend!(Y)

Thanks

TimPalmer
July16,2016at3:47pmReply

Yousaid"thecompilerresolvesthisexpression"Doesthismeanthatforexample

1 x=2+3;

wouldbesimplifiedto

1 x=5

aftercompiled?Imeanratherthanatruntime.

Alex
July18,2016at5:01pmReply

Yep.

mostafakaram
July21,2016at5:40amReply

#include<iostream>
intmain()
{
std::cout<<"helloworld!"
return0
}
.
.ididprintthesamecodebutitisstillnotworking
andthenididprintthiscode
#include<iostream>

usingnamespacestd

intmain()
{
cout<<"helloworld"
cin.get()
return0
}
anditdidwork..isitbecauseiusevisualstudio2012orwhat

Alex
July22,2016at9:20pmReply

ThoseprogramsshouldbothworkinVisualStudio2012.Areyousureyoudidntincludeiostream.hby
accident?

sajibsaha
July27,2016at8:33pmReply

inturboc++thereisnoneedtoenter

usingnamespacestdorstd::beforecout

and#include"iostream.h"replaces"iostream"

anditrunsfine..amIcorrect?

Alex
July30,2016at10:19pmReply

Yes,becauseTurboC++isnoncompliantwithmodernstandards.

Deepu
July28,2016at2:53amReply

Underthefunctionsparagraph

Helpfulhint:Itsagoodideatohaveyourmain()functionliveina.cppfilewiththesamenameasyourproject.

Ididntgraspbywhatyoumeantbythatsentence,perhapsyoucouldelaboratewithanexample.

Alex
July30,2016at10:31pmReply

e.g.Ifyourewritingachessgame,putyourmainfunctioninchess.cpp.

Skella
August2,2016at6:55amReply
HeyAlex,Firstofall,Thanksfortipsandtutorials,reallyenjoyed.
second,iwasjustconfusedonthepart


1.isthestd::cout<<HelloAlex<<std::endlanewerwayofputtingjustcout<<HelloAlex<<endl?whats
therecommendedone?

Thankyou.

Alex
August3,2016at1:46pmReply

Itsbettertousethestd::prefix.Itslessambiguous,asitmakesitclearexactlywhatyourereferring
to,sothecompilerdoesnthavetoinferyourintent.

chuks
September30,2016at1:23pmReply

Lovely.Ijustflowwiththeexplanation.Soeasy!

AarJay
October14,2016at12:56pmReply

Alex.Thanksforwritingthesegreattutorials.Juststartedlearning.Soheregoesasillyquestion:
Doesitmatteriftheoutputoperatoriswrittenonaparticularsideoftheobjectstd::cout,whichrepresentsthe
screen?Imeanwillitbesyntacticallycorrecttowriteastatementlikethis:"Printthis">>std::cout

Alex
October14,2016at2:15pmReply

Yes,itdoesmatter.Operator<<isusedforoutput,whereasoperator>>isusedforinput.

AarJay
October14,2016at10:11pmReply

Thanksforreplying.ButsorryIerredinwritingmyquestion.ImeantsaythatIwillstillusethe
outputoperator<<withstd::cout,butcanIwriteitonleftsideofstd::cout?Likethisstatement:
"Printthistoscreen"<<std::cout

Alex
October17,2016at11:35amReply

Nope.Forthisoperator,std::cout(oranotherstreamobject)mustbeonthelefthandsideof
operator<<.

homayou
October18,2016at10:56pmReply

thanksalotiloveit

Jumboh
October20,2016at2:39pmReply

Greattutorial

Mahesh
November5,2016at6:33pmReply

ThanksAlex..GreatWork!!

GEScott71
November14,2016at4:01amReply

ThanksAlex,forthetutorialandthecommentssectionImlearningalotfromthecommentsandyourreplies
too.

DevilHand
November19,2016at7:01amReply

Isiostreamalibraryinitselforapartofthec++standardlibrary?
Oritisaheaderfile?(Ifyesthenwhatdoesheaderfilesactuallymean?)
Andwhatisthedifferencebetweenheaderfilesandlibraries?
Regards.
P.S.Thetutorialsareamazingamazingamazing.Alreadylearnedalot!

Alex
November19,2016at10:33amReply

iostreamisaheaderfilethatispartoftheC++standardlibrary.Wetalkaboutheaderfilesindetaillater
inthischapter.Librariesaretypicallyprecompiledcodethatyoucanlinkintoyourprogram.Italkabout
librariesinappendixA.

DevilHand
November19,2016at5:45pmReply

Butinonecommentyousaidthatcoutandendlliveintheiostreamlibrary.
Itsconfusing!

Alex
November20,2016at1:32pmReply

ThanksforclarifyingyourconcernIthinkImisunderstoodwhatyouwereasking.Letme
seeifIcanclarifyfurther.

TheC++standardlibraryisinternallydividedintodifferentareas,eachofwhichisalsoinformallycalleda
libraryeventhoughitsjustpartofthestandardlibrary.Sowhenwetalkabouttheiostreamlibrary,were
reallytalkingaboutthepartoftheC++standardlibrarythatcontainsC++sstreaminginput/output
functionality.Thatfunctionalityisaccessedbyincludingtheiostreamheaderinyourprograms.Doesthat
makesense?

N
November27,2016at3:13amReply

HellothereAlex!IwonderifcanIcanuseallyourmaterials(withyourpermissionofcourse)tohelpmy
studentlearntheC++PL(thoseexplanationwhereverysimpleandeasytounderstand[minusthe
technicalitiesIfoundinmyProgrammingBooks)bythewaysIamanITInstructorandoneofmysubjectis(incidentally)
C++.Iwillalsomentionthisgreattutorialsofyourstomystudent.Thanks!Keepupthisawesomework!

Das könnte Ihnen auch gefallen