You are on page 1of 45

1.

3Afirstlookatvariables,initialization,andassignment
BYALEXO NMAY30T H,2007| LAST MO DIF IEDBYALEXO NNO VEMBER15T H,2016

Variables

Astatementsuchasx=5seemsobviousenough.Asyouwouldguess,weareassigningthevalueof5tox.Butwhat
exactlyisx?xisavariable.

AvariableinC++isanameforapieceofmemorythatcanbeusedtostoreinformation.Youcanthinkofavariableasa
mailbox,oracubbyhole,wherewecanputandretrieveinformation.Allcomputershavememory,calledRAM(randomaccess
memory),thatisavailableforprogramstouse.Whenavariableisdefined,apieceofthatmemoryissetasideforthevariable.

Inthissection,weareonlygoingtoconsiderintegervariables.Anintegerisanumberthatcanbewrittenwithoutafractional
component,suchas12,1,0,4,or27.Anintegervariableisavariablethatholdsanintegervalue.

Inordertodefineavariable,wegenerallyuseaspecialkindofdeclarationstatementcalledadefinition(wellexplainthe
precisedifferencebetweenadeclarationandadefinitionlater).Heresanexampleofdefiningvariablexasanintegervariable
(onethatcanholdintegervalues):

1 int x;

WhenthisstatementisexecutedbytheCPU,apieceofmemoryfromRAMwillbesetaside(calledinstantiation).Forthe
sakeofexample,letssaythatthevariablexisassignedmemorylocation140.Whenevertheprogramseesthevariablexinan
expressionorstatement,itknowsthatitshouldlookinmemorylocation140togetthevalue.

Oneofthemostcommonoperationsdonewithvariablesisassignment.Todothis,weusetheassignmentoperator,more
commonlyknownasthe=symbol.Forexample:

1 x = 5;

WhentheCPUexecutesthisstatement,ittranslatesthistoputthevalueof5inmemorylocation140.

Laterinourprogram,wecouldprintthatvaluetothescreenusingstd::cout:

1 std::cout << x;// prints the value of x (memory location 140) to the console

lvaluesandrvalues

InC++,variablesareatypeoflvalue(pronouncedellvalue).Anlvalueisavaluethathasanaddress(inmemory).Sinceall
variableshaveaddresses,allvariablesarelvalues.Thenamelvaluecameaboutbecauselvaluesaretheonlyvaluesthatcan
beontheleftsideofanassignmentstatement.Whenwedoanassignment,thelefthandsideoftheassignmentoperatormust
beanlvalue.Consequently,astatementlike5=6willcauseacompileerror,because5isnotanlvalue.Thevalueof5
hasnomemory,andthusnothingcanbeassignedtoit.5means5,anditsvaluecannotbereassigned.Whenanlvaluehasa
valueassignedtoit,thecurrentvalueatthatmemoryaddressisoverwritten.

Theoppositeoflvaluesarervalues(pronouncedarrvalues).Anrvaluereferstoanyvaluethatcanbeassignedtoanlvalue.
rvaluesarealwaysevaluatedtoproduceasinglevalue.Examplesofrvaluesaresinglenumbers(suchas5,whichevaluates
to5),variables(suchasx,whichevaluatestowhatevervaluewaslastassignedtoit),orexpressions(suchas2+x,which
evaluatestothevalueofxplus2).

Hereisanexampleofsomeassignmentstatements,showinghowthervaluesevaluate:

1 int y;// define y as an integer variable


2 y = 4;// 4 evaluates to 4, which is then assigned to y
3 y = 2 + 5;// 2 + 5 evaluates to 7, which is then assigned to y
4
5 int x;// define x as an integer variable
6 x = y;// y evaluates to 7 (from before), which is then assigned to x.
7 x = x;// x evaluates to 7, which is then assigned to x (useless!)
8 x = x + 1;// x + 1 evaluates to 8, which is then assigned to x.

Letstakeacloserlookatthelastassignmentstatementabove,sinceitcausesthemostconfusion.

1 x = x + 1;
Inthisstatement,thevariablexisbeingusedintwodifferentcontexts.Ontheleftsideoftheassignmentoperator,xisbeing
usedasanlvalue(variablewithanaddress).Ontherightsideoftheassignmentoperator,xisbeingusedasanrvalue,and
willbeevaluatedtoproduceavalue(inthiscase,7).WhenC++evaluatestheabovestatement,itevaluatesas:

1 x = 7 + 1;

WhichmakesitobviousthatC++willassignthevalue8backintovariablex.

Programmersdonttendtotalkaboutlvaluesorrvaluesmuch,soitsnotthatimportanttoremembertheterms.Thekey
takeawayisthatontheleftsideoftheassignment,youmusthavesomethingthatrepresentsamemoryaddress(suchasa
variable).Everythingontherightsideoftheassignmentwillbeevaluatedtoproduceavalue.

Initializationvs.assignment

C++supportstworelatedconceptsthatnewprogrammersoftengetmixedup:assignmentandinitialization.

Afteravariableisdefined,avaluemaybeassignedtoitviatheassignmentoperator(the=sign):

1 int x; // this is a variable definition


2 x = 5; // assign the value 5 to variable x

C++willletyoubothdefineavariableANDgiveitaninitialvalueinthesamestep.Thisiscalledinitialization.

1 int x = 5; // initialize variable x with the value 5

Avariablecanonlybeinitializedwhenitisdefined.

Althoughthesetwoconceptsaresimilarinnature,andcanoftenbeusedtoachievesimilarends,wellseecasesinfuture
lessonswheresometypesofvariablesrequireaninitializationvalue,ordisallowassignment.Forthesereasons,itsusefulto
makethedistinctionnow.

Uninitializedvariables

Unlikesomeprogramminglanguages,C/C++doesnotinitializevariablestoagivenvalue(suchaszero)automatically(for
performancereasons).Thuswhenavariableisassignedtoamemorylocationbythecompiler,thedefaultvalueofthatvariable
iswhatevergarbagehappenstoalreadybeinthatmemorylocation!Avariablethathasnotbeenassignedavalueiscalledan
uninitializedvariable.

Note:Somecompilers,suchasVisualStudio,willinitializethecontentsofmemorywhenyoureusingadebugbuild
configuration.Thiswillnothappenwhenusingareleasebuildconfiguration.

Uninitializedvariablescanleadtointeresting(andbyinteresting,wemeanunexpected)results.Considerthefollowingshort
program:

1 // #include "stdafx.h" // Uncomment if Visual Studio user


2 #include <iostream>
3
4 int main()
5 {
6 // define an integer variable named x
7 int x;
8
9 // print the value of x to the screen (dangerous, because x is uninitialized)
10 std::cout << x;
11
12 return 0;
13 }

Inthiscase,thecomputerwillassignsomeunusedmemorytox.Itwillthensendthevalueresidinginthatmemorylocationto
cout,whichwillprintthevalue.Butwhatvaluewillitprint?Theansweriswhoknows!,andtheanswermaychangeevery
timeyouruntheprogram.WhentheauthorranthisprogramwiththeVisualStudio2013compiler,std::coutprintedthevalue
7177728onetime,and5277592thenext.

Acoupleofnotesifyouwanttorunthisprogramyourself:

Makesureyoureusingareleasebuildconfiguration(seesection0.6aBuildconfigurationsforinformationon
howtodothat).Otherwisetheaboveprogrammayprintwhatevervalueyourcompilerisinitializingmemorywith(Visual
Studiouses858993460).

Ifyourcompilerwontletyourunthisprogrambecauseitflagsvariablexasanuninitializedvariable,apossible
solutiontogetaroundthisissueisnotedinthecommentssection.

Usinguninitializedvariablesisoneofthemostcommonmistakesthatnoviceprogrammersmake,andunfortunately,itcanalso
beoneofthemostchallengingtodebug(becausetheprogrammayrunfineanywayiftheuninitializedvaluehappenedtoget
assignedtoaspotofmemorythathadareasonablevalueinit,like0).

Fortunately,mostmoderncompilerswillprintwarningsatcompiletimeiftheycandetectavariablethatisusedwithoutbeing
initialized.Forexample,compilingtheaboveprogramonVisualStudio2005expressproducedthefollowingwarning:

c:vc2005projectstesttesttest.cpp(11):warningC4700:uninitializedlocalvariable'x'used

Agoodruleofthumbistoinitializeyourvariables.Thisensuresthatyourvariablewillalwayshaveaconsistentvalue,makingit
easiertodebugifsomethinggoeswrongsomewhereelse.

Rule:Initializeyourvariables.

Quiz
Whatvaluesdoesthisprogramprint?

1 int x = 5;
2 x = x - 2;
3 std::cout << x; // #1
4
5 int y = x;
6 std::cout << y; // #2
7
8 // x + y is an r-value in this context, so evaluate their values
9 std::cout << x + y; // #3
10
11 std::cout << x; // #4
12
13 int z;
14 std::cout << z; // #5

QuizAnswers

Toseetheseanswers,selecttheareabelowwithyourmouse.

1)ShowSolution

2)ShowSolution

3)ShowSolution

4)ShowSolution

5)ShowSolution

1.3aAfirstlookatcout,cin,andendl

Index

1.2Comments

Sharethis:
Facebook Twitter Google Pinterest

C ++TU TOR IAL | PR IN TTH ISPOST

195commentsto1.3Afirstlookatvariables,initialization,andassignment

Lol
November14,2007at8:29amReply

TheCode:

#includestdafx.h
#include

intmain()
{
usingnamespacestd
cout>x//readnumberfromconsoleandstoreitinx
cout

ItDosentWork

newuser
February14,2008at6:56pmReply

Whenyouusethecoutcallfromtheoutputstreamthedirectionalindicatorneedstobe<.The>isfor
thecincallfromthelibrary.

Ravi
January17,2009at2:33amReply

1 Yes, your code would work man!


2 try this one,
3
4 #include "stdafx.h"
5 #include <iostream> //you have not included the library file..
6
7 int main()
8 {
9 using namespace std;
10 int x;//i think you have to declare x....
11 cout << x;//then you can do whatever you like to...
12 return 0; //not included...
13 }

csvan
April23,2009at3:43amReply

Youforgottoinitializex(ie.x=7)!Ialsothinkitisbetterifyouputusingnamespacestd
OUTSIDEmain,tomakeitglobal.

Quinn
July10,2009at7:15pmReply

Idisagree.Thiscanveryeasilyinlargerprogramscausecrypticerrorsfromnameconflicts.
Keepingusingnamespacewithinfunctionslimitsitsscope,andthuslimitsitspotentialfor
causingproblems.Thesafest,though,istosimplyalwaysrefertothenamespaces,i.e.std::cout<<x
instead.

venki
November10,2016at4:30amReply

cout>x
iswrongusage."<<"thisoperatorisusedtooutputthevalue

Kyle
November28,2007at6:32pmReply

Whenitryandrunthecodetoenteranumberandhaveitbedisplayeditisntworkingright.Aboxopensand
itasksmynumberanditypeitinandtheboxjustcloses.Notsurewhatimdoingwrong.

Ravi
January17,2009at3:01amReply

TrythefollowingKyle,itwillsurelywork:

1 #include "stdafx.h"
2 #include <iostream>
3
4 int main()
5 {
6 using namespace std;
7 cout << "Enter a number: "; //it will ask you to enter no..
8 int x; //declaring x as integer..
9 cin >> x; //asking the user for the value of x..
10 cout << "You have entered: " << x << endl; //displays your value and also ends the l
11 ine
12 return 0;
}

Ravi..

csvan
April23,2009at3:46amReply

No,unfortunatelyitwillnot.Hisproblemwasthattheprogramclosedimmediatelyafterinput.Itis
mostlikelybecausehehasanIDEwhichbreaksprogramexecutionimmediatelyaftermain()
returns0.Assuch,hewouldneedtoeitheruseapausefunctionsuchassystem(PAUSE)toprompttheuser
topressenter,beforetheprogrambreaksexecution.

Alex
January4,2015at11:48amReply

system(pause)mayworkonsomesystems(e.g.windows),butnotonothers.

Abetter(platformindependent)solutionispresentedinsection0.7Afewcommoncppproblems.

Darren
June2,2016at6:16amReply

IfusingVisualStudiothenthisisthedefaultbehaviourtheprogramexitsandterminatestheconsole
windowimmediately.YoucanremedythisbygoingtothePropertySheetfortheVSproject(rightclick
thesolutionnameinthe"SolutionExplorer"paneandclick"Properties"atthebottomofthesubmenu)selectlinker
>systemandthefirstfieldinthesheetshouldread"SubSystem"withadropdownmenuicon.Clicktheiconand
selecta"Console"subsystemandokaythechange.Youwillhavetorecompileproject(shortcutkeyf7)butnowif
yourunitusingctrlf5theconsolewillhangaftertheprogramhasfinished,allowingyoutoreadtheoutput.Notethat
pressingf5alonewillnotmaketheconsolehang.

Lol
December15,2007at3:47amReply

ItdoesentWork.

WhenisTryitsays
internumberhereienterthenumberandthePrgCloses

csvan
April23,2009at3:52amReply

Lol,whichIDEandwhichOSareyouusing?UnderWindows,youcanuseafunctioncalled
system(PAUSE)inordertopausetheprogrambeforeitgoeson(inyourcase,exits).

Inyourcase,youthenfirstneedtowritethefollowinginthebeginningoftheprogram:

1 #include <cstdlib> <!--formatted-->

ThiswillincludetheCstandardlibraryintoyourprogram.

Then,beforethereturnstatementinmain(),addsystem(PAUSE),assuch:

1 int main()
2 {
3 // Some code here...
4
5 system("PAUSE");
6 return 0;
7 }
8 <!--formatted-->

Thatshoulddoit.However,thebadthinghereisthatIthinkthisworksONLYonWindowsnotgood!Also,Ihave
heardthatthesystem()functionisveryunsafeandshouldgenerallybeavoidedinprofessionalprojects,whichis
perhapsnotsoimportantherebecauseyouarejuststudying.

Hopethathelps!Ifyouneedmorehelpyoucanmailme(csvanefalk@hushmail.me)orofcourseasktheownerof
thesite(Alex).MeandAlexarenotaffiliatedinanyway,Iwouldjustliketohelpout Dontforgettogivetheprops
toAlexforhisgreatsitethough!

azzy
December31,2007at12:18amReply

firstthelinelookswrong
itshouldbecout>>xnotcout>x

Second,theprgclosesifyouareusingVS2005orasimilarIDE.VS2005createsanewconsolewindowwhentheprogram
startsandclosesitassoonastheprogramfinishes.Thecodeexecutedperfectly.Justthatassoonasitprintstheoutput,
theprogramhasfinishedanditclosesleavingyounotimetoseeit.youneedtomakeitpauseusingacinfunction.

iwrotemyownterminatingcode:

//forterminatingtheapplication
cout<>exitapp
cout<<"terminating"<

Timon
January2,2008at2:27pmReply
itdidntworkwhenitriedit.

Alex
January2,2008at4:10pmReply

Timon,Iaddressedthisissueinsection0.7

Timon
January3,2008at5:43amReply

Whereat?Andthecauseoftheproblemseemstobe:

cin>>exitapp

1 #include "stdafx.h"
2 #include <iostream>
3
4 int main(){
5 using namespace std;
6 cout << endl << endl << endl << "Type something and Press Enter to Terminate" <
7 < endl;
8 string exitapp;
9 cin >> exitapp;
10 cout << "terminating" <<endl;
}

Alex
January3,2008at7:13amReply

Answer1insection0.7talksaboutamethodtokeepthewindowopenattheendof
yourprogram.Isthatnotwhatyourissueis?

Timon
January3,2008at7:58amReply

Ok.Thanks!

ChuckNelson
January4,2008at4:39pmReply

Whythevalueof858993460whendisplayinganuninitializedint?

Itisnottheminint.Isthereareasonitisthisvalue?

Thankyou!

Alex
January5,2008at10:10amReply

Memoryisreallyjustasequenceofbinarybitsstrungtogether,andmemorygetsreusedoften.Soyour
intvariablexmightusethesamememorylocationassomeothervariablewasusingjustamoment
ago.Ifthevariablexisnotinitialized,itinherits(inthenonobjectorientedsense)whatevervaluewasthere
previously.

Forexample,letssaytherewas8bitsofmemorythathadthisvalue:00000101.
IfyoudeclaredcharchValue,andthevariablechValuewasassignedtothismemoryaddress,thenchValuewillstart
withtheuninitializedvalue5,because00000101binary=5decimal.

Asaconsequenceofthis,youneverknowwhatvalueanuninitializedvariablewillprintbecauseitdependson
whateverhappenstoalreadybeinmemorythevariableisusing.Itmaychangeeverytimeyouruntheprogram.It
maychangeonlyoccasionally.Butyoucanalwayscountonitbeingsomethingyoudontwant!

renu
January7,2008at12:19pmReply

MyquestionissameasChucks.Itriedthisanditisprinting858993460.Whyisitprintingaparticular
numberifitisagarbagevalue?Isthereaspecificreasonforthat?Itriedit34timesandeverytimeitprints
858993460.
Thanks,
Renu

Alex
January7,2008at2:04pmReply

Becausethisvariableisnotallocateddynamically,itsbeingallocatedonthestack.Lotsofstuffisput
inthestack,includingfunctioncallinformation,returnaddresses,etcIpresume(andthisisjustan
educatedguess)thatthefactthatweareallseeingthesamenumber(858993460)hassomethingtodowiththeway
theprogramortheOSissettingupthestackbeforetheprogrambeginsexecuting.PerhapstheOSiscleaningout
thestacktoensurethatwedontrecoversensitiveinformationfromapriorprogramsexecution?

Asanaside,although858993460seemslikeareallybizarrenumber,itsactuallyjust0xCCCCCCCCinhex(which
isbitpattern11001100110011001100110011001100).

Tom
January26,2009at1:40pmReply

ThisisfeatureofbuildingdebugC++softwarewithVisualStudio.Anythingyoudontinitialiseyourself
issetto0xCCCCCCCC(interpretedas858993460ifitsanint).

Tryswitchingthebuildtypefromdebugtorelease,andthevaluewillbetrulyuninitialisedandmaychangeeachtime
yourunit.

me
January16,2008at6:10amReply

Igotalittleprobhere:
wheniruntheprogramitasksmetoenteranumberandwhenidoandpressenter,theprogramcloses..?
(iuseDevC++4.9.9.2)

Thx,
Me

Alex
January16,2008at7:51amReply

Seesection0.7,firstanswer.

abdy
February1,2008at9:06amReply

hey,everytimeirunthiscodeikeepgetting5fortheanswer.
myguessisthatitskeepingxstoredfromthepreviousexercise,butshouldntthecin.clearthatyousaidto
usegetridofthat?
#include

intmain()
{
usingnamespacestd
inty//declareyasanintegervariable
y=4//4evaluatesto4,whichisthenassignedtoy
y=2+5//2+5evaluatesto7,whichisthenassignedtoy

intx//declarexasanintegervariable
x=y//yevaluatesto7,whichisthenassignedtox.
x=x//xevaluatesto7,whichisthenassignedtox(useless!)
x=x+1//x+1evaluatesto8,whichisthenassignedtox.
cin.clear()
cin.ignore(255,\n)
cin.get()
return0
}

Alex
February1,2008at9:26amReply

Hiabdy.Thisprogramshouldntoutputanythingsinceyoudonthaveanycoutstatements,soIamnot
surehowyoukeepgetting5fortheanswer.Ifyouaregettingoutput,thenIsuspectyoureactually
compilingandrunningadifferentproject.Somecompilersletyoukeepmultipleprojectsopensimultaneously.Make
suretheprojectyouwanttocompileistheactiveone(usually,rightclickonitandchoosesetasactiveprojector
somethingsimilar).

Thecin.clear()cin.ignore(255,\n)cin.get()linesjustforcetheprogramtopauseatthebottomsoyoucanseethe
outputbeforethewindowcloses.

TikiBarber
April7,2008at8:47amReply

WheneverItrytocompiletheprogramthatoutputstheinputvariable

1 #include "stdafx.h" // Uncomment this line if using Visual Studio


2 #include
3
4 int main()
5 {
6 using namespace std;
7 cout <> x; // read number from console and store it in x
8 cout << "You entered " << x << endl;
9 return 0;
10 }

Itgivesmethiserror..

1>LINK:fatalerrorLNK1104:cannotopenfilekernel32.lib

Anyideas?

Alex
April7,2008at8:22pmReply

Itsoundslikeyourlinkerproperties/directoriesaresetupincorrectly.

Youmightseeifthisisyourproblem.

Saguna
March15,2010at1:25amReply
seeyourcout<>Thisseemstobewrong

r86k
June19,2008at1:38pmReply

1 #include <iostream>
2 using namespace std;
3
4 int main(void)
5 {
6
7
8 cout << "Enter a number: " << endl;
9 int x;
10 cin >> x;
11 cout << "You entered " << x << endl;
12
13 system ("pause");
14 return 0;
15 }

Joyel
June27,2008at8:35pmReply

Youcuoldhaveprobablywentintoalittlemoredetailaboutthose2functionsbutyoudidagoodjobofgetting
usontherighttracktostartwith.

Lumos
September19,2008at12:59pmReply

Trytousesystem()assmallaspossible.Itwillbebetter(inoursituation)tousegetch()whiclallocatedat
conio.h

Alex
September21,2008at10:09amReply

conio.hisnotpartoftheC++standardsetoflibraries,andisnotincludedwithallcompilers.
ConsequentlyIwouldrecommendavoidingitsusewheneverpossible.

fluxx
October9,2008at11:45pmReply

Wouldthiswork?thankyou!

1 #include <iostream>
2
3 using namespace std;
4
5 int calculate()
6 {
7 int length;
8 int width;
9 int area;
10 area = length * width;
11 return 0;
12 }
13
14 int main()
15 {
16 cout << "hi and welcome to my rectangle area calculator" << endl;
17 cout << "please enter the length of the rectangle:" <<
18 cin >> "length" <<;
19 cout >> "thank you!" << endl;
20 cout >> "please enter the width of the rectangle:" << endl;
21 cin >> "width" <<;
22 cout << "after a SPECTACULAR calculation the machine came up with the following answer:" <
23 < area << endl;
24 return 0;
25
26 }
<!--formatted-->

Tyler
December30,2008at12:04pmReply

heyfluxx,

Assoonasisawyourcodeiwentatittryingtofixit.andtomypleasentsuprize,igotitworking.

hereistheperfectedcode:

1 #include <iostream>
2
3 int main()
4 {
5 using namespace std;
6 cout << "Hi and welcome to my rectangle area calculator" << endl;
7 cout << "please enter the length of the rectangle: ";
8 int l;
9 cin >> l;
10 cout << "thank you" << endl;
11 cout << "please enter the width of the rectangle: ";
12 int w;
13 cin >> w;
14 cout << "after a SPECTACULAR calculation the machine came up with the following answ
15 er:" << l * w << endl;
16 system ("pause");
17 return 0;
18
} <!--formatted-->

firstofall,thewholeintcaculatepartwascompelelyuselessandunessary.second,useingnamespacestdis
supposttobeaffterintmain().third,manyofyourslashbrackatsarewrong,whenuseingcout,allslashbrackets
arefacingtheleft.Aboutthesystem(puase)partneartheend,dependingonwhatcompileryouareuseingyou
maynotneedittobethere.imuseingacompilerthatrequiresmetoinputapuasecode.butevenifyourcompiler
dosenotneedit,itshouldenthurtanything.

jacob
June21,2009at11:30pmReply

ProofthativeactuallylearnedsomethingfromthistutorialalthoughincIcanmakeitsoyoucan
typebooththenumbersonthesamelinebutImstilllearningbothlanguagesatthesametimeXD

1 #include <iostream>
2
3 int main()
4
5 {
6
7 using namespace std;
8 cout << "welcome to rectangle area calculator enter the first number: " ;
9 int x ;
10 cin >> x;
11 cout << " enter the second number: " ;
12 int b ;
13 cin >> b ;
14 int y;
15 y = x * b;
16 cout << "the area is: " << y << endl ;
17
18 }
19 <!--formatted-->

Noah
December7,2008at4:14pmReply

Imadethis

1 #include "stdafx.h>
2 #include <iostream>
3
4 int main()
5
6 {
7
8 using namespace std;
9 cout << "Enter a Number: " ;
10 int x;
11 cin >> x;
12 cout << "This is The Number Multiplied by Two: "<< x * 2 << endl;
13 return 0;
14 } <!--formatted-->

Anditworked!!!

Quinn
July10,2009at7:26pmReply

1 #include "stafx.h>

O_o

Isupposeakindcompilerwillacceptthat.Kindofunconventionalthough.

Justin
February27,2009at9:58amReply

Hialexiwouldliketoaskyousomthingwheniput:

intx
x=5

itgivesmethiserror25D:\DevCpp\main.cppexpectedconstructor,destructor,ortypeconversionbefore=token

andiamgreatlyconfusedplzhelp

Thankz

Justin
C++learner

Alex
March1,2009at12:15pmReply

Idontseeanythingwrongthere,exceptthatyoudonthaveasemicolonafterx=5.
Leo
March29,2009at12:23pmReply

So,itisoptimaltousetheminimumamountofvariables,whencreatingaprogram,tomakeitlighton
resources(RAM)?

Alex
May1,2009at8:24pmReply

Onlyifyouhaveareallyhugenumberofvariables(eg.inthethousands).Otherwiseitwontmake
muchdifference.

cameronfitzpatrick
July3,2015at1:01pmReply

dudeurpcitureisthefunniestthingihaveEVERseen

even8yearslater

Mike
April19,2009at7:28amReply

HeyAlex,greatsiteyouhavehere!IwastakingaC++classyearsago,butassoonaswegottopointersI
gaveup.Sincethen,Ihaveincreasedmyknowledgeabit,atleastwithpython/javascript,soIfiguredI
wouldgiveC++anothergo.Anyways,imlearningalotmoreherethenIdidinschool,sothanksforthesite!

Also,asfaraspausingisconcerned,Ireadthistechniquesomewere

1 #include "stdafx.h"
2 #include <iostream>
3 #include <conio.h>
4
5 using namespace std;
6
7 // Our custom built pause function
8 static void pause()
9 {
10 cout << "Press any key to close this window..." << endl;
11 _getch();
12 }
13
14 int main()
15 {
16 cout << "Hellow World." << endl;
17
18 pause(); // Call our custom pause function before close
19
20 return 0;
21 }

Theysaidtheirreasoningisitwouldbecrossplatformcompilable,becausepause.exeiswindowsspecific,andalsoif
someone/somethingweretotamperwithpause.exe,executingpause.execouldbedangerous.

Itseemstoworkwell,whatareyourthoughts/opinionsonit?

Alex
May1,2009at9:36pmReply

Itllworkinthemajorityofcases,andyes,itsbetterthanusingpause.exe.
Theonlytimeitllfailisifthereareextracharactersintheinputbuffer_getch()willreadthemandnotstopformore
input.

Ipresentaslightlyimprovedversionofthisinlesson0.7afewcommoncppproblemsthatfixesthatparticular
issue.

Sadlyenough,thepausingissueisbyfarthemostcommontopiconthissite.

jacob
June21,2009at11:08pmReply

Thankyouwhoeverwrotethis.Gaveaverywellexplanationonwtfwasgoingon.Cissimilarbutcppmakes
variablesmuchsimpler

Jason
August21,2009at1:44amReply

HiAlex,iamnewtoC++,pleasecouldyouexplaintomewhyyouusedthefollowinglines:

y=4//4evaluatesto4,whichisthenassignedtoy
y=2+5//2+5evaluatesto7,whichisthenassignedtoy

aslateryousaythaty=7whichitdoesbutify=4..theny=2+5=7
whydidwehavetousey=4?

regards,
Jason

BR
November6,2009at7:18pmReply

TheideawastoshowthatifyoureassignavaluetoY,thenitwillchange.

1 y = 4; // the value of Y is now 4.


2 y = 2+5; // 2+5 = 7, so the value of Y is now 7, making the previous assignment invalid.

rose
September28,2009at9:04amReply

Alex,
dothis#includealonework?
ytheyrntgivinganythingaftrtht?
whatdoes#includealonemean?

Thanks

Alex
January4,2015at11:58amReply

#includebyitselfmeansnothing,andisntvalidC++.Thecompilerwillthrowanerror.

MichaelM
November1,2009at11:41pmReply

Alex,youareamazing.Thankyousomuchforwritingthesetutorials.

Ivespentalmosttwohoursreading(andrereadinguntilImadesureIunderstoodwhatyouaretryingtosay)chapter1.3
andbelow.Thatmightseemlikealotoftime,butIwanttoknow100%whatImdoing.

Im14yearsoldandonedayIdlovetoworkatajobhavingtodowithprogramming(ImlookingatValveSoftwareright
now).IknewnothingatallaboutC++,butverylittleJava,soIthoughtIshouldstarthere.Hopefullythesetutorialswillgive
meagoodstart,andIwillcontinuetolearnandpracticeC++untilIreachmygoal.Iunderstandthatmakinggameswith
C++maybeverydifferentfromwhatyoureteaching,butlikeIsaid,Imhopingthesetutorialswillgivemeagoodstart.

Excusemytyping,its2:40AMandImabittired.Irememberedwhatyoumentionedatthebeginningofthetutorialabout
beingtiredand/orunhappy.

Cantwaitfortomorrow!

Ok_im_confuzed_about
January5,2010at7:09amReply

Oksoifyourvaluesareassignedtoarandommemoryaddressifwemakethevaluejustxthenhowwillyou
findit?

Alex
January4,2015at11:59amReply

Wedontneedto.Wecallthevariablebyname(x),andtheprogramitselfkeepstrackofwherein
memorythevariablepoints.

MattF
February4,2010at3:02amReply

1 // math.cpp : Defines the entry point for the console application.


2 //
3
4 #include "stdafx.h"
5 #include <iostream>
6
7 main()
8 {
9 using namespace std;
10 int x = 5;
11 x = x - 2;
12 cout << x << endl; // #1
13
14 /*int y = x;
15 cout << y << endl; // #2
16
17 // x + y is an r-value in this context, so evaluate their values
18 cout << x + y << endl; // #3
19
20 cout << x << endl; // #4
21
22 int z;
23 cout << z << endl; // #5
24 */
25 }
26 <!--formatted-->

Ikeepgettinganerrormessage:errorC4430:missingtypespecifierintassumed.Note:C++doesnotsupportdefaultint
anderrorC2065:cout:undeclaredidentifier
anderrorC2065:endl:undeclaredidentifier
Idontknowwhythefirstonegettingnumbersworkedfinebutthisonedoesnotatall,allitriedtodowaserasetheoldstuff
andenterthenewstuff.

AdamSinclair
August16,2010at8:56amReply

Youforgotthe

1 int main()
Youjusthave:

1 main()

Jack
March28,2010at6:31pmReply

1 #include <stdafx.h>
2 #include <iostream>
3
4 int main()
5
6 {
7 using namespace std;
8
9 cout << "Please enter your age:" << endl;
10 int x;
11 cin >> x;
12 cout << "Please enter your name:" << endl;
13 int y;
14 cin >> y;
15 cout << "Hello " << y << ", you are " << x << "-years-old." << endl;
16
17
18
19
20 return 0;
21
22 }

Itdoesntseemtolikewords.WheneveryoutypeyournameinitgivesyouabunchofnumbersbackisthereanythingI
cando?

adam
April1,2010at4:12pmReply

ThereareseveralvariabletypesinC++,inthiscaseyouredeclaringanintegervariable(avariablethat
onlystoresnumbers)sowhenyouretryingtooutputthatvariableitgivesyoucrazystuff.

Gizmo
November24,2010at4:02amReply

Hello,Jackyouwrotethis.

#include
#include

intmain()

{
usingnamespacestd

cout<<"Pleaseenteryourage:"<>x
cout<<"Pleaseenteryourname:"<<endl
inty>y
cout<<"Hello"<<y<<",youare"<<x<<"yearsold."<<endl

return0

Allyouhavetodoischange(intytochary[20])Idontknowthatsthisisthebestwaybutitworksforme.
Gizmo
November24,2010at4:19amReply

Sorry,IforgottheHTMLtagsletstryagain.

Hello,Jackyouwrotethiscode.

1 #include <stdafx.h>
2 #include <iostream>
3
4 int main()
5
6 {
7 using namespace std;
8
9 cout << "Please enter your age:" << endl;
10 int x;
11 cin >> x;
12 cout << "Please enter your name:" << endl;
13 int y;//<----------------------------------------------------------- Change int
14 y; to char y [20];
15 cin >> y;
16 cout << "Hello " << y << ", you are " << x << "-years-old." << endl;
17
18 return 0;
19
}

IhopeIusedthetagsrightifnotsorry.

SolomonHomicz
May21,2010at9:35amReply

Ivegotaproblemnobodyelseseemstohave.ImfollowingthistutorialwithbothanIDEandatext
editor/commandterminal.ImrunningUbuntu10.04withQtCreatorforanIDE,andgeditforaneditor.
WhenIcompilethegeditversionoftheprogrammanuallyusingg++ofirstfirst_C_prog.cppitrunsandworksjustfine.
WhenIbuildessentiallythesamecodeintheIDEitbuildsfineandrunsbutwhenIputinanumberandhitenteritjustgoes
toanewline.Itdoesntdisplayanythingbacktothescreenandkeepsrunning,Ihavetokillitmanually.
Heresthecode,theonlydifferenceisinthemanuallycompiledversionIremovethe#includeQtcore(seemslikethesame
thingasstdafx.h).

1 #include <QtCore/QCoreApplication>
2 #include <iostream>
3
4 int main ()
5 {
6 using namespace std;
7 cout << "Hello World!" << endl;
8 int x = 0;
9 cout << "Enter a number: ";
10 cin >> x;
11 cout << "Your number is: " << x << endl;
12 return 0;
13 }
14 <!--formatted-->

ImgoingtodigintotheIDEhelpnext,andseeifIcanfigureitout.Imanengineeringstudentandhavebeenprogramming
extensivelyinFortran,soaneditorandterminalisjustfinebyme,butIthinkanIDEisgoingtobeessentialifIwantto
makeajumptoGUIapplications.
TheprofessorssayifyoucanprograminFortranyoucanprograminanything,anditseemslikeC++isthebackboneof
justabouteverything.MostpeopledontcareaboutthingslikeRombergintegrationorfinitedifferenceina3dmatrixthey
justwantaprettywindowontheircomputerscreenthatgivesthemananswer.So,ImofftolearnC++andthisisthebest
tutorialIvefound,thanxAlex.
AnybodyhavesuggestionsonhowtomakethisIDEbehave?
Darren
June2,2016at7:30amReply

awwwfortranlikethegrandparentwhorefusestodieandtriestodressuplikethekidswiththeir
fancydynamicmemoryallocation,objectorientateddesign,easytouseandformatfilei/o,smart
pointers,lambdas,.whichisjustawkwardforeveryoneconcerned.

sega
July14,2010at8:53pmReply

WhenassigninganumbertoxIcantassignthenumber9999999999toit.Ifigurethatitistoolargeofa
number.Isthereawaytogetaroundthis?

senthil.cp
March21,2012at3:23amReply

hisega,

ihavenewlyregisteredtodayonly.
andihavefoundthisgreatwebsitetolearnc++
allthecredittoalex

pleasecheckifmysolutionsuitsyourproblem

doublex=9999999999
cout<<setprecision(16)
cout<<"value="<<x

Alex
January4,2015at12:01pmReply

Usethetypelonginsteadofint.Wecoverthis(andothertypes)inmoredetailinlesson2.4
Integers.

AdamSinclair
August16,2010at8:50amReply

1 #include "stdafx.h"
2 #include <iostream>
3
4 using namespace std;
5
6 int main()
7 {
8 int x;
9 cout << x << endl;
10 }

WhenIrunthiswithVisualC++2008,theconsoleopensupanditdoesntsayanything.Onlysays:

PressEntertocontinue

UnderMotion
August24,2010at6:29amReply

1 using namespace std;


shouldbeinbetweenthebracketsinmain()
Tryitout

lisyhave
November10,2010at2:01amReply

Whydoesntthiswork??havetriedtochangesomefunctionsbutitistakenfromthesolutionfromquestion5.

#includeStdAfx.h

#include

intdoubleNumber(intx)
{
return2*x
}

intmain()
{
usingnamespacestd
intx
cin>>x
cout<<doubleNumber(x)<>x
x=doubleNumber(x)
cout<<x<Buildstarted:Project:igne,Configuration:DebugWin32
1>igne.cpp
1>c:\users\mathias\desktop\projects\igne\igne\igne.cpp(24):errorC2084:functionintmain(void)alreadyhasabody
1>c:\users\mathias\desktop\projects\igne\igne\igne.cpp(13):seepreviousdefinitionofmain
==========Build:0succeeded,1failed,0uptodate,0skipped==========

Maggie
December21,2010at10:52pmReply

Thefollowingismycode:

#includestdafx.h
#include

intdoubleNumber(intx)
{
return2*x
}

int_tmain(intargc,_TCHAR*argv[])
{
usingnamespacestd
intx
cin>>x
cout<<doubleNumber(x)<<endl
x=doubleNumber(x)
cout<<x<<endl
return0
}

Bytheway,maybeyourproblemisthe"main"function,pleasecheckyourcode,andmakesure
Goodluck!
Alex
January4,2015at12:04pmReply

Soundslikeyouhavefunctionmain()declaredtwice,onceatline13andonceatline24.

JLaughters
April23,2011at6:36amReply

WhenIrunthisprogramitlookslikeIinputanumberandalwaysgetoutputof0.
Itshouldtaketheuserinputinfunctioninput1andsaveittovariablea.Thenreturnatomaintobecout.I
addedacoutininput1aftertheuserinputtoseeiftheusersinputswasbeingstoredasa.Itwas.Itseemsthoughthat
whenaisreturnedtomainaisbeingresetto0.

1 #include "stdafx.h"
2 #include <iostream>
3
4 int input1(int a)
5 {
6 using namespace std;
7 cin >> a;
8 return a;
9 }
10 int main()
11 {
12 using namespace std;
13 int a = 0;
14 input1(a);
15 cout << a;
16
17 return 0;
18 }

senthil
March21,2012at3:52amReply

youareprintingthelocalcopyofaandnotthereturnvalue.Thelocalcopyofaisinitializedto0and
notchangedanywhereinthemain.hence0isdisplayed.

solution:
updatethelocalcopyofawiththereturnvalue.

a=input1(a)
cout<<a

rameye
November1,2014at12:55amReply

Orsimplypassthevariabletoinput1()byreferenceinsteadofbyvalue.Likethis:

#include<iostream>

voidinput1(int&a)
{
usingnamespacestd
cin>>a
}
intmain()
{
usingnamespacestd
inta=0
input1(a)
cout<<a

return0
}

Helleri
July12,2011at11:46pmReply

Whatdoesthelinlvalueandtherinrvaluestandfor?rightandleft?

alsoIdontgethowIcangoasfarastocopythethingIwassupposedtodoexactlyandtherearebuilderrorsor
something.Itseemtodotheexactsamethingthelastprogramdid

whatdoescoutstandfor?whatdoescinstandfor?whyis<<sometimesfacingonewayandsometimesfacinganother
withoutanobviousreason?

zingmars
July19,2011at2:54amReply

1)Yes,rvaluestandsforrightvalue,andlvaluestandsforleftvalue.
2)Whaterrorsareyoutalkingabout?Didyoucopyonlythecodewithoutthelinenumbers?didyou
removetheVSpart?
Itsquitepossiblethattheauthorhadsometypos,butitmightbeaproblemonyourendtoo.
3)cstandard(dontaskme),outoutput,ininput.Asfor>>and<<'Ican'treallyexplainwhyisthat.

Yahsharahla
August5,2011at11:59amReply

Hiafterseveralattemptsofmyprogramnotrunningafterquestion#1onthequizIfinallygotittorunby
using:

#include"stdafx.h"
#include<iostream>

intmain()
{
usingnamespacestd
intx=5
x=x2
cout<<x<<endl//#1
cin.clear()
cin.ignore(255,'\n')
cin.get()
inty=x
cout<<y<<endl//#2
cin.clear()
cin.ignore(255,'\n')
cin.get()
cout<<x+y<<endl//#3
cin.clear()
cin.ignore(255,'\n')
cin.get()
cout<<x<<endl//#4
cin.clear()
cin.ignore(255,'\n')
cin.get()
intz
cout<<z<<endl//#5
cin.clear()
cin.ignore(255,'\n')
cin.get()
return0

seegoing
August16,2011at9:29pmReply

Q:whydoesdeclaringavariableusing
int(A)
workthesameas
intA

???shouldtherebeadifferencebetweenthetwodeclarationstatements,espgiventhatthevariablenameisenclosedin
brackets?

zingmars
August20,2011at7:25amReply

Idontthinkthattheresadifference,no.Still,enclosingavariablenameinbracketslookskindofsilly
andisredundant.

Alex
January4,2015at12:09pmReply

Declaringavariableasint(a)isinvalid,andyourcompilershouldcomplain.

ahoora
September15,2011at7:51amReply

Iamsogladtofindyourwebsite.Thereisaverylogicalrationalebehindyourexplanationwhichmakesit
simplerandatthesametimejoyfultolearn.

Manythanksforallthehardandsmartwork.

marki123
September22,2011at12:33pmReply

whenicompiledtheprogramthatusesthecincout.ienterthenumberthenpressenterandsuddenlythe
programcloses.andthisisthecodeicompiled.pleasetellmeifthereisanythingwrongwithit.(imusingcode
blocksbutonwindows)

#include

intmain()
{
usingnamespacestd
cout<>x
cout<<"YouEntered"<<x<<endl
return0
}

zingmars
October8,2011at4:09amReply

Thatsbecausetheresnothingthatpreventstheprogramfromclosingafterthecoutruns.IIRC
Code::Blockshadabugwhichwouldsometimesbugoutthethingthatsresponsibleforkeepingthe
windowuponcethecodehasbeenexecuted(cinrelatedtoo,Ithink).
Justputacin.ignore().get()afterthecoutline.
Homesweetrichard
December29,2011at10:09amReply

#include

intvariables()
{
usingnamespacestd

cout<>b

inte
e=b*10

intl
l=e/100

inta
a=e+b

intd
d=l+e

ints
s=2*(da)

intm
m=b+l

cout<<b<<e<<l<<a<<d<<s<<m

return0

mukulgarg_jec
May8,2012at1:36amReply

youaremissingmain()function.Updatedcodeis

#includestdafx.h
#include
intmain()
{
usingnamespacestd

cout<>b

inte
e=b*10

intl
l=e/100

inta
a=e+b

intd
d=l+e

ints
s=2*(da)

intm
m=b+l

cout<<b<<e<<l<<a<<d<<s<<m
return0

AIKS
February10,2012at6:19amReply

whyismain()functionprecededbyint?myreferencebooksshowtheuseofvoid.doesitmakeany
difference?

Alex
January4,2015at12:15pmReply

main()isprecededbyintbecauseitreturnsanintegervaluetotheoperatingsystemwhentheprogram
terminates.

Italkaboutthisinsection1.4afirstlookatfunctions.

voidmain()isinvalidC++(althoughsomeMicrosoftcompilersacceptit).Yourreferencebooksareincorrect.

ballooneh
March13,2012at6:42pmReply

Onecommontrickthatexperiencedprogrammersuseistoassignthevariableaninitialvaluethatisoutside
therangeofmeaningfulvaluesforthatvariable.Forexample,ifwehadavariabletostorethenumberofcats
theoldladydownthestreethas,wemightdothefollowing:

1
intcats=1
Having1catsmakesnosense.Soiflater,wedidthis:

1
cout<<cats<<"cats"<<endl
anditprinted1cats,weknowthatthevariablewasneverassignedarealvaluecorrectly."

Couldanyonehelpexplainthistome?Iseriouslyneedhelponthis.Talktomelikea10yearoldifyoucan

Alex
January4,2015at3:54pmReply

Imagingyourewritingaprogramwhereyourekeepingtrackofhowmanycatsarebeingadoptedout
today.

1 nCats = 0; // default to no cats adopted out today


2
3 // Do some stuff here
4
5 cout << "We adopted out << nCats << "cats today!" << endl;

Youruntheprogram,anditprints,Weadoptedout0catstoday!.Isthiscorrect,orhaveyoumadeanerror
somewhereanddoneacalculationwrong?Itsnotclear.

Nowconsiderthisprogram:

1 nCats = -1; // We can't adopt out a negative number of cats


2
3 // Do some stuff here
4
5 cout << "We adopted out << nCats << "cats today!" << endl;

Ifthecodeprints,Weadoptedout0catstoday!,youknowyoureallydidntadoptoutanycats.
Ifthecodeprints,Weadoptedout1catstoday!,youknowtheresaprobleminyourprogramsomewhere,because
nCatsshouldhaveneverbeenleftwiththevalueof1.
Landru598
January12,2015at5:27pmReply

Thankyouforthesetutorials,theyarestraightforwardandincludewhatyouhavetoknow.BythetimeIfinish
allofthesesectionsshouldIbeabletoprogramgameslikepingpong?

Ethanicus
January13,2015at5:04pmReply

Hey,Alex.

Inoticedthatyousaid
std::cout<<cats<<"cats"
anditprinted1cats.

Howwouldyouchangeavariabletobetext?Forinstance,
intname="Joe"
std::cout<<"Hello,"<<name<<std::endl
soitwillsay"Hello,Joe."
Ican'tseemtogetittowork.

Alex
January14,2015at4:52pmReply

Thatsbecauseyouvedeclarednameasaninteger(number),notastring(sequenceofletters).Italk
moreaboutstringsinsection6.6Cstylestringsandanintroductiontostd::string.

Unfortunately,inC++,stringsaremorecomplicatedthantheyshouldbe.

Darren
June2,2016at7:41amReply

Useapointertoacharactertypee.g.

1 char* name = "Joe";

whichisequivalentto

1 char name[] = "Joe";

Alternatively(andIrecommendthisbecausechar*areapaininthebum)usethestringclassdefinedinthestandard
headere.g.

1 #include <string>
2 ...
3 std::string name = "Joe";
4 //or
5 std::string name2("another joe");

Paul
January24,2015at3:03amReply

Initialisinga(real)variablewith1isinmyopinionnotthebestpractice.
Forperformanceonemaychooseaunsigneddatatypeand1willnotworkwiththis?Soyouwillhaveto
switchtosignedjusttobeabletotellifitsdeclared?

Anybetteroptions?Probablydeclaringwithastandardvalueor0?

Catreece
February17,2015at7:14amReply
Disappointmentget.

SawtheprogramtospitoutwhatevernumberXgetsdefinedtoanddecidedtorunitmyselfoutofcuriousity.
ItwouldseemVisualStudio2013hassincefixedthisissueandwillrefusetocompile,statingthatXis
undefined.

Shame,that.Itwould'vebeenthefirstthingIdideverytimeIsatdowntolearnmoreprogrammingstuff,justtesttosee
whatXistoday.

Iwonderifthere'sanywaytogetaroundtheerror?

errorC4700:uninitializedlocalvariable'x'used

Itusedtoworkonolderversions,sothisimpliesthatsomethingaboutthesourcecodeofthecompilerchangedtolookfor
thatissue,which'sagoodthing,mostly.Italsoimpliesthatitmaythereforebepossibletoflatouttellittorunthatlineand
ignorewhatevererrorsitgets.

Actually,nowI'malsocuriousifit'sGOODorBADthatI'mactivelytryingtothinkofwaystobreakthecompilerformy
ownentertainmentProbablybad.Ohwell.

Alex
February17,2015at1:10pmReply

Trythis:

1 // #include "stdafx.h" // Uncomment if Visual Studio user


2 #include <iostream>
3
4 void doNothing(const int &x)
5 {
6 }
7
8 int main()
9 {
10 // declare an integer variable named x
11 int x;
12
13 // trick the compiler into thinking this variable is used
14 doNothing(x);
15
16 // print the value of x to the screen (dangerous, because x is uninitialized)
17 std::cout << x;
18 }

WhenIranthisonVS2013(releaseconfiguration),Igot7177728.

Catreece
February18,2015at6:46amReply

Huh,interesting.MaybeIjustrandomlygotanunreadablechunkofmemoryanditgotpissyabout
anonintergervalue?Great,nowIneedtotestthisagain.=P

Yep,lookslikethatwasit.Testingaaaand858993460

Thanks,Icould'vegonemylifewithoutknowingthis.Bloodyenabler!XD

Seriouslythough,thankyou,IguessIjustgotunluckythefirsttime=3

Alex
February18,2015at5:26pmReply

858993460isthevaluethatVisualStudioinitializesmemorywithwhenrunningprogramsin
adebugconfiguration.

Switchtothereleaseconfiguration(Seesection0.6aBuildconfigurationsifyouneedhelponhowto
dothat)andtryagain.
Stepc0re
October1,2016at8:24amReply

Nowitreturns0everytime=(

Alex
October3,2016at12:45pmReply

Thatsokay.Printingthevalueofanuninitializedvariableresultsinundefined
behavior.Thatcouldbearandomvalue,oritcouldbe0dependingonwhatthe
memorywasusedforbeforehand.Itmayalsochangeasyoualteryourprogramandrecompile.

macks2008
February28,2015at5:33pmReply

Whatisbadabouthavingfuntryingtounderstandwhat'sgoingon(by"breaking"thecompiler)?Isn't
thattheentire*point*oflearningaprogramminglanguage?Ifyouthinkit'sbadtohavefun
circumventingrestrictionsplacedononeselfbyprogrammers(oftheIDE),Ithinkyoumightbeonthewrongboat.
Takechances,makemistakes,getmessy!(Great,nowI'mquotingchildren'sshows)

Chris
February17,2015at11:25pmReply

Thecommentsinthecodeforthislessonaren'tthey"bad"?Seemstomeyoucommentedagainsthowyou
advisedtocommentinthepreviouslesson.Furthermorethe//commentsthattakeup2linesdonotturngreen
invisualstudio.Whatgives???

Alsothecode:

1 // #include "stdafx.h" // Uncomment if Visual Studio user


2 #include <iostream>
3
4 void doNothing(const int &x)
5 {
6 }
7
8 int main()
9 {
10 // declare an integer variable named x
11 int x;
12
13 // trick the compiler into thinking this variable is used
14 doNothing(x);
15
16 // print the value of x to the screen (dangerous, because x is uninitialized)
17 std::cout << x;
18 }

WhenIrantheabovecodejustasisinVisualStudiouncommentingthepartIneededtoitrancorrectlybutthecmdwindow
instantlyshutdown,notgivingmeenoughtimetoseetheoutput.Ihadtomodifyitasfollows:

1 #include "stdafx.h"
2 #include <iostream>
3
4 void doNothing(const int &x)
5 {
6 }
7
8 int main()
9
10
11
12 {
13 //declare an integer variable named x
14 int x;
15
16 //trick the compiler into thinking this variable is used
17 doNothing(x);
18
19 /*print the value of x to the screen
20 (dangerous, because x is uninitialized)*/
21 std::cout << x;
22
23 std::cin.clear();
24 std::cin.ignore(255, &apos;\n&apos;);
25 std::cin.get();
26
27
28 }

But....Ididn'thavetomodifytheHelloWorldcodetomakemyoutputboxstayopenlongenoughtoviewit.Couldyoutell
mewhy?

Alex
February18,2015at4:51pmReply

Yes,thecommentsIusethroughoutthecodeexamplesarehorriblebynormalstandards!Butthats
becausemygoalhereistoteachyouhowthingswork,andcommentsareanintegralpartofthat
process.

Noideawhytheconsoleforoneofyourprogramsstayedopenandtheotherdidnt.Iveneverhadanissuewith
visualstudioclosingmyconsoles,assumingIveexecutedtheprogramfromtheIDE.Runningtheexedirectlyis
anotherstory.

TwistedCode
April8,2015at9:11pmReply

Isitacceptabletotakeadvantageoftheabilitytouseanuninitializedvalueanduseitforapseudorandom
function?

Alex
April9,2015at11:48amReply

Thisisntagoodidea.Thebehaviorofuninitializedvariablesisundefined,soyoucantassume
anythingaboutthem,includingwhethertheyllbesuitablyunpredictable!

Ifyouwantapseudorandomgenerator,useawellestablishedone,likeMersenneTwister.Seesection5.9
Randomnumbergenerationformoreinformationaboutthis.

TwistedCode
April13,2015at8:15pmReply

Yeah,Ikindoffiguredthattheundefinednaturewouldbeaninherentproblem,butIfiguredId
throwitoutthere.Mightevenbeworthincludingasalittlenoteinthebodyofthelesson?idk

Tito
April13,2015at6:57amReply

Perhapsyoushouldalsointroducecharactervariablesinthissectionaswell?WhenIgottowardstheendof
thechapterwiththecalculatoritwouldhavebeenhelpful.Someonepostedaprettygoodexampleinthe
comments,anditwassimpleenoughafterIknew"char".
Alex
May19,2015at8:30amReply

Iagreeitwouldbehelpfulinsomecases,butforthischapter,simplicityisthekey.Addingchar
introducessomecomplexityfornotmuchgainatthispoint.

Odgarig
May19,2015at3:44amReply

Hello,ImreallythankfultoyouforlettinguslearnC++.Iwasdoingfinesofartillendofthissection.AndI
haveaquestion.InQuiz1wedefinexas5(isarvalue=>Ijustkeepingmyselfrememberit)andx=x2.And
wereprintingxonaconsole.AndwhatIthoughtwasitwouldbeawrongcodebecausexassignedto5whichmeansthe
lastdefinedvariableequalsto5=53whichmeanscantbetrue.AndwhenIcheckedtheanswer,itsoutputwas3.An
anotherquestionisthecodewritteninthequizsectionwouldnthavea{atthebeginningofthecode(Imeanaftermain()
function)and}attheendofthecode?.IwouldbeveryhappywithyouranswerANDTHANKYOU.

Alex
May19,2015at8:33amReply

Goodquestion.Inthestatement:

1 x = x - 2;

xisbeingusedintwodifferentcontexts.Ontheleftside,xisbeingusedasanlvalue(variable).Ontherightside,x
isbeingusedasanrvalue,andisbeingevaluatedonlyforitsvalue.

SoC++isntevaluatingthisas5=52,itsevaluatingitasx=52,whichmakesalotmoresense.Illtryto
clarifythisinthelessonitself.

Odgarig
May23,2015at3:45amReply

Thankyoufortheanswer.IwonderifitworkssameinC#.

Alex
June8,2015at4:44pmReply

ItworksthesamewayinC#.

hobbiest
June6,2015at6:13amReply

Iamtryingtoruntheprogramfromthelessonabove(uninitializedvariable)butamreceivinganerrorfromthe
line:
#include"stdafx.h"

thecompilercannotfindstdafx.h

Theactualerrormessageis
Error1errorC1083:Cannotopenincludefile:stdafx.h:Nosuchfileordirectoryc:\users\pc\documents\visualstudio
2013\projects\project1\project1\source.cpp11Project1

IamusingMSVisualStudio(2013)

Anysuggestions?

Thanks\!
Alex
June8,2015at4:45pmReply

Therearealotofreasonsthiscouldhappen.IdpastetheerrorintoGoogleandseeifanyofthe
articlesthatcomeuphelpyouresolvethis.

Hobbiest
June13,2015at12:43pmReply

Maybeabetterquestioniswheredidstdafx.hcomfrom.Orwheredoanyofthe#includeprograms
(functions?)comefrom?Ididnotcreateit,Ididnotloadityettheprogramneedsittorun.

BythewayonthisexampleIcommenteditoutanditrunsfine.

Again,thanksforhelpingmeunderstandthis.

Alex
June15,2015at12:59pmReply

.hfilestypicallycomefromoneoftwoplaces:libraries(likethestandardlibrary)orfilesthatyoucreate
yourselfaspartofyourprogram.

However,stdafx.hissomethingthatVisualStudiouseswhenprecompiledheadersareturnedon.Ifyourenotusing
VisualStudio,youdontneedit.Andifyouare,youcanjustleaveitblankfornow.Youwontneedtoworryaboutit
untilyourprogramsgetlarge.

newprogrammer
June17,2015at4:50amReply

Isitpossibletodeclareavariableinthemiddleofastatement(likebelowdeclaringxasintthenpassingitto
cout)ordoesthedeclarationstatementalwaysneedtobeonitsownstatementline?
thanks

1 std::cout << int x = 8 << std::endl;

Alex
June17,2015at1:46pmReply

Yourlineofcodeisactuallyanexpression,andvariablescantbedeclaredaspartofanexpression.

Variablesmustbedeclaredinastatement.

chirag
June17,2015at11:33pmReply

//HelloWorld.cpp:Definestheentrypointfortheconsoleapplication.
//

#include"stdafx.h"
#include<iostream>

intmain()
{
intx=5
x=x2
std::cout<<x<<std::endl
inty=x
std::cout<<y<<std::endl
std::cout<<x+y<<std::endl
std::cout<<x*y<<std::endl
intz=x+y
std::cout<<z<<std::endl
inta=x+y*z
std::cout<<a<<std::endl
return0
}
theansweris21whyy*zwasmultipliedfirstthanxwasadded

Alex
June20,2015at12:00pmReply

Thisishowmathematicsworksinreallife.Multiplicationanddivisionbeforeadditionandsubtraction.

Theresanacronymthatmakesiteasytoremembertheorderofmath:PEDMAS.Parenthesis,exponent,division,
multiplication,addition,subtraction.

gigi
July7,2015at6:04amReply

Canyouaddreturn0inyourexample?

1 // #include "stdafx.h" // Uncomment if Visual Studio user


2 #include <iostream>
3
4 int main()
5 {
6 // define an integer variable named x
7 int x;
8
9 // print the value of x to the screen (dangerous, because x is uninitialized)
10 std::cout << x;
11 }

Alex
July7,2015at10:27amReply

Fixed.Thanks!

Brian
July8,2015at8:58pmReply

Wow,greattutorialonvariables!IhaveworkedwithC++beforebutwastotallyunawarethatuninitialized
variablescouldslippastthecompiler.

KingRon
July13,2015at12:37pmReply

ItriedthisbutInevergotaresultevenafterswitchingittothereleaseconfiguration

#include"stdafx.h"
#include<iostream>

voiddoNothing(constint&x)
{
}

intmain()

{
//declareanintegervariablenamedx
intx
//trickthecompilerintothinkingthisvariableisused
doNothing(x)

/*printthevalueofxtothescreen
(dangerous,becausexisuninitialized)*/
std::cout<<x

std::cin.clear()
std::cin.ignore(255,&apos\n&apos)
std::cin.get()

Pofke1
July25,2015at4:55amReply

Imusingvisualstudio2015anditseemstonotmakerandomvariableswhentheyrenotset.Sowheniuse

1 // #include "stdafx.h" // Uncomment if Visual Studio user


2 #include <iostream>
3
4 int main()
5 {
6 // define an integer variable named x
7 int x;
8
9 // print the value of x to the screen (dangerous, because x is uninitialized)
10 std::cout << x;
11
12 return 0;
13 }

itsays:
errorC4700:uninitializedlocalvariablexused
butwheniaddx=5etcitprints5..
justsaying.

Alex
July27,2015at10:28amReply

Yes,thisisalreadyaddressedinthearticle.Ishowaworkaroundinthecommentssectionabove.

Kerberos
August2,2015at8:27pmReply

Hi.Ihaveaproblemunderstandingthiserror:
Programisnotrecognizedasaninternalorexternalcommand,operableprogramorbatchfile(9009)

ThispopsupwhenItrytostartmyprogramfortheselittlequizzes.

1 #include "stdafx.h"
2
3 int main()
4 {
5 int x = 5;
6 x = x - 2;
7 std::cout << x << endl;
8 }

Thanksinadvance.

Alex
August3,2015at8:47amReply
ItsoundslikeVisualStudiocantfindyourexecutable,howevertherearelotsofreasonsthatcould
happen.

Afewthingstocheck:
1)DidyoucreateaWin32consoleproject?
2)Whenyoucompiledyourprogram,diditactuallycreatean.exefile?(Ifitcreateda.dllinstead,youcreatedthe
wrongtypeofproject).
3)Openyourprojectpropertiesandmakesurethatyourstartuppathiscorrect.

Kerberos
August3,2015at11:03amReply

Ohthankyou,Mr.Alex!Iwasabletofixmyprogram.=DIforgottotype"std"infrontofendl.

Kerberos
August3,2015at10:43amReply

IcreatedaWin32consoleapplication.WasIsupposedtocreateaWin32projectinstead?

WhenIstartedtheprogramwithoutdebugging,thecmd.exewindowdisplayeditasan.exefile.

WhenIstarttheprogram:

"c:[].exe"isnotrecognizedasaninternalorexternalcommand,operableprogramorbatchfile.

Isthestartuppathsameasanetworkpathorlocationaddress?

1 #include "stdafx.h"
2 #include <iostream>
3 int main()
4 {
5 int x = 5;
6 x = x - 2;
7 std::cout << x << endl;
8 return 0;
9 }

Rohit
August6,2015at12:15amReply

"InC++,variablesareatypeoflvalue(pronouncedellvalues)."pronouncedellvalue(no"s").

Alex
August6,2015at10:03amReply

Thanks,fixed!

Rohit
August6,2015at10:48pmReply

Orithinkthisisbetter:
"InC++,variablesareatypeoflvalues(addeds)(pronouncedellvalues)."

Rohit
August6,2015at10:45pmReply

1 int x = 5;
2 x = x - 2;
3 std::cout << x << endl; // #1
4
5 int y = x;
6 std::cout << y << endl; // #2
7
8 // x + y is an r-value in this context, so evaluate their values
9 std::cout << x + y << endl; // #3
10
11 std::cout << x << endl; // #4
12
13 int z;
14 std::cout << z << endl; // #5

Itshowederrors:

error:endlwasnotdeclaredinthisscope|

Soiusedstd::endlanditworked.But"z"wasprinting"0"everytime.

Alex
August7,2015at9:39pmReply

zhasntbeenassignedavalue.Soitllprintwhateverhappenstobeinthememorylocationthatis
assignedtoz.Inmanycases,thatwillbe0,butitcouldbeanything.

Rohit
August9,2015at5:31amReply

AreyousuresameisthecasewithC++11?Maybetheyhavenowchangedthis!Nowitmay
assigndefaultvalue"0".

Alex
August9,2015at11:42amReply

Yes,Imsure.

Ifyourunyourprograminadebugbuildconfiguration,thecompilermayinitializeyourvariablesto0for
you.Itwontdothisinareleaseconfiguration.

daniel
August9,2015at6:16amReply

wellnewtocoding/programmingstuff,callmeanubbutiamhavingconfusionthis:

intx

weuse,this"int"whatdoesitstandsfor?integerorinitialize?

Alex
August9,2015at11:42amReply

Integer.

daniel
August10,2015at1:33amReply

anotherquestionsir,
Quiz:
Solution3.
questionitevaluatesto6?butpreviousstatementwedeclaredinty=xsoywasalsorepresentingx?orywas
representingactualvalue3?

OR
wedeclaredxandybothforvalue3?soifwehavetoaddressorrepresent3wecanusexorwecanusey?

Alex
August10,2015at11:41amReply

Online2,xwasassignedthevalueof3.
Online5,ywasassignedthevalueof3(notx).
So,online9,x+yevaluatesto3+3,whichis6.

Theresnoindirectiongoingonhere.Justvariablesthatholdintegervalues.

daniel
August10,2015at10:32pmReply

gotit,thanks.

Darius
August20,2015at2:32amReply

Howdyfolks,whatamidoingwrong,idontseemabletoaddlinebreaks!!

1 #include "stdafx.h"
2
3
4 #include <iostream>
5 int main()
6 {
7 int x;
8 x = 8;
9 std::cout << x << endl;
10 return 0;
11 }
12 /*1>------ Build started: Project: ConsoleApplication1, Configuration: Debug Win32 ------
13 1>ConsoleApplication1.cpp
14 1>c:\c\consoleapplication1\consoleapplication1.cpp(12): error C2065: 'endl': undeclared identi
15 fier
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========*/

Alex
August20,2015at8:53amReply

replaceendlwithstd::endl.endlispartofthestandardlibrary,soitlivesinthestdnamespace.

soham
August30,2015at7:31pmReply

whenwillibeabletomakeagameofmyown

Kidane
September4,2015at12:23amReply

WhatisthedifferenceifIput

usingnamespacestd

beforemain()functionandinsidemain()function?
Alex
September4,2015at12:43amReply

Thisiscoveredinthenextlesson.

Danual
October12,2015at6:46pmReply

HiAlex!

Sorry,butthismaybeconfusingtosome:"Avariablecanonlybeinitializedwhenitisdefined.",thisimpliesthatavariable
mustbeinitializedwhenthevariableisdefined,i.e.onthesamelineasdefiningit.

Alex
October14,2015at12:01pmReply

>Thisimpliesthatavariablemustbeinitializedwhenthevariableisdefined,i.e.onthesamelineas
definingit.

Itmorethanimpliesititsaysitoutright. Variablemustbeinitializedatthepointtheyaredefined.Afterthe
variablehasbeendefined,yourenotinitializingit,youreassigningvaluestoit.Inmanycases,theendresultisthe
same.Butwellseecaseslaterwherevariablesmustbeinitialized(suchasconstvalues,orreferences)forthis
reason,itsimportanttounderstandthedistinction.

Whatdoyoufeelisconfusingaboutthestatement?

ryder
October16,2015at7:35pmReply

verygood

fateme
October22,2015at3:03amReply

whichoneweuseisbetter?usingnamespacestdorstd::?

Alex
October22,2015at1:15pmReply

std::isbetterfromanambiguitystandpoint,butusingcanbeeasiertoread.Whichyouuseissituation
dependent.Ialmostalwaysusestd::,andonlyuseausingstatementifIhaveafunctionthat
referencesstd::alotoftimes,andforwhichallthosereferencestostd::isimpedingreadability.

JosephDaniel
October22,2015at5:59amReply

1 #include"stdafx.h"
2
3 #include <iostream>
4 int main()
5 {
6 int x;
7 x = 10;
8 int z;
9 z = x + 8;
10 std::cout << z;
11 return 0;
12 }

Thisdoesntworkandhastheerror:LNK1120unresolvedexternalatline1
andSeverityCodeDescriptionProjectFileLine
ErrorLNK2019unresolvedexternalsymbol_WinMain@16referencedinfunctionint__cdeclinvoke_main(void)(?
invoke_main@@YAHXZ)TestprojectE:VisualStudioProjectsTestprojectTestprojectMSVCRTD.lib(exe_winmain.obj)1

Alex
October22,2015at2:27pmReply

Itlookslikeyourehavingalinkererrorwhereitcantfindyourmain()functionforsomereason.Isthe
filethatthismain()functionisinaddedtoyourproject?

Tryrecreatingyourprojectandseeifthatworks.

sajjadhussain
October27,2015at11:19amReply

1 // ConsoleApplication2.cpp : Defines the entry point for the console application.


2 //
3
4 #include "stdafx.h" // Uncomment if Visual Studio user
5 #include <iostream>
6
7 int main()
8 {
9 int x = 5;
10 x = x - 2;
11 std::cout << x << endl;
12
13 int y;
14 y = x;
15 std::cout << y << endl;
16
17 return 0;
18 }

Whatswrongwithit?
ITsshowingthefollowingerror:
1>ConsoleApplication2.cpp(15):errorC2065:endl:undeclaredidentifier
1>ConsoleApplication2.cpp(11):errorC2065:endl:undeclaredidentifier

Alex
October27,2015at12:53pmReply

endllivesinthestdnamespace,soitneedstobecalledasstd::endl.

Ellochain
December25,2015at4:03pmReply

Hithere.

ImusingthelatestversionofCodeBlocks.
Buildtargetsetto"Debug".

Followingcodeshowsthevalueoftwouninitializedvariablesxandy.

1 #include <iostream>
2
3 int main()
4 {
5 int x;
6 int y;
7 std::cout << x << " - " << y <<std::endl;
8 return 0;
9 }

Result:
42858382752404

Irunitafewtimesoverandalwaysgetthesamenumbers,whichisreasonablelikeyouexplainedabove.
ThenIswitchxandyinthecoutexpressionlikethis:

1 #include <iostream>
2
3 int main()
4 {
5 int x;
6 int y;
7 std::cout << y << " - " << x <<std::endl;
8 return 0;
9 }

Tomysurprisetheresultremainsunchanged:
42858382752404

Sowhatsgoingonhere?
Ithoughtthememoryallocationhappenedassoonastheprogramencounteredthevariabledeclaration.Butifthatweretrue
thenumbersshouldhavebeenswitchedjustlikethevariables.Perhapsmemoryallocationhappensonlywhenthevariable
getscalledthefirsttime?Oristhisastackthing?

Alex
December26,2015at2:08pmReply

Noidea. Maybewhenyourcompilergeneratescode,itsdoingitinorderofuseratherthanorderof
declaration?

ak
December27,2015at12:58pmReply

#include<iostream>

usingnamespacestd

intmain()

{
intv=0
charo=0.0
floatp=0.0

cin>>v>>o>>p

return0
}

aftertakingfirsttwoinputsitterminates..whycantitakethe3rdone?

Alex
December28,2015at3:56pmReply

Itworksfineformewithsampleinput:5(enter)j(enter)4.4(enter).Whatinputareyougivingit?

Trung
January13,2016at3:10amReply
1 #include <iostream>
2 #include <conio.h>
3 using namespace std;
4 int main()
5 {
6 int x;
7 int y;
8 cout << " X + Y = 6";
9 cout << " \n Value X " << endl;
10 cin >> x;
11 cout << " Value Y = " << 6 - x;
12 cin >> y;
13 return 0;
14 }

Hehe.Myexerciseforthistopic.
IcandoitYeYe

selty
February16,2016at12:11amReply

ithelpsealot

MayurB.
February22,2016at5:13amReply

whatIrememberfromC++Primer,Ibelieve

1 int x;

isadeclaration.And

1 int x = 5;

isdefinition(Declaration+Initialization).
PleasecorrectmeifImwrong.AlsoIdontknowhowmuchimportantthesetermsare?Pleasespecify.

MayurB.

Alex
February24,2016at9:59amReply

Youarecorrect.Wetalkmoreaboutthedifferencebetweendeclarationsanddefinitionsinlesson1.7.
Thetermsareimportanttoknow.

Nyap
March4,2016at12:58pmReply

Howmuchramdoesonevariabletakeup?

Alex
March6,2016at2:22pmReply

Itdependsonthesizeofthevariable.Wediscussthisinmoredetailinchapter2.

Nyap
March8,2016at11:19amReply

k.also,couldyoubeabitmorespecificonwhatactuallyhappensduringinstantiation?ordowe
alsolearnthatinanotherlesson?thnx

Alex
March9,2016at2:35pmReply

Howvariablesgetinstantiatedunderthehoodisabitcomplex.Allyoureallyneedtoknowat
thispointisthatmemoryissetasideforthevariable,sothevariablecanbeused.

mangix
March22,2016at3:45amReply

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

IwrotetheaboveinthelatestCode::Blocks(16.01)withgcc5.1onWindows1064bit.Ialwaysgot0insteadofrandom
outputnomatterinDebugorReleasemode.Anyideas?

Alex
March22,2016at4:19pmReply

Printinganunassignedvariableresultsinundefinedbehavior.Undefineddoesnotmeaninconsistent.
Yourmachinemightalwaysprint0,butanothercompilermightdosomethingelseentirely.

Nyap
March22,2016at9:58amReply

xisuninitialized

VidyaMoger
March31,2016at6:15amReply

Whenavariableisdeclared,doesCPUsetasideapieceofmemoryinstack?IfsothenIhaveasilly
questionhere..
AsstackfunctionalityisFirstInLastOut,howvaluespushedintostackarefetchedbecauseaprogramcanuseany
variableatanypointoftimeduringexecution?Idontknowifmyquestionmakesanysense!!!!!!

Ifnotinstack,thenwhichpartofmemoryisusedforprograms?

Thanksinadvance

Alex
March31,2016at8:51amReply

Thisiscoveredmuchlaterinthetutorial.Shortanswer:globalvariables(whichcanbeaccessedany
time)arentkeptonastack.Localvariables(whichcanonlybeaccessedinalimitedscope)arekept
onthestack.

c++begginer
April16,2016at5:32amReply

verygoodexplanationsitseasytounderstand

Ayush
June5,2016at2:32amReply

WhenIcompiledmyprogrammeusingdebugbuildconfigurationincodeblocksthenitshowedthevalue
4309678butwhenIshiftedtoreleasebuildconfigurationthenitshowedthevalue0.

Steffen
July5,2016at2:49pmReply

WhenIwritethecodeinVC2015likethisIgetanC4700error.

(Becausezisuninitialized)

Whyisthat?ShouldntIstillbeabletoruntheprogram?OramIdoingsomethingwrong?

TheCode:

#include"stdafx.h"
#include"iostream"

intmain()
{
intx=5
x=x2
std::cout<<x<<std::endl

inty=x
std::cout<<y<<std::endl

std::cout<<x+y<<std::endl

std::cout<<x<<std::endl

intz
std::cout<<z<<std::endl

return0
}

Andonemorething:WhenIpush"Startwithoutdebugging",whydoesVCtellsmetheprojectisoutofdateandaskmeifI
liketorunitanyway?

Thanks

Alex
July6,2016at1:20pmReply

VisualStudiotreatsusesofuninitializedvariablesasanerror.Someothercompilerstreatitasa
warning.TheresprobablyawaytomakeVisualStudiotreatitasawarninginsteadofanerror,butI
wouldntadvisechangingit.

Asfortheissuewithprojectsbeingoutofdate,therearemanyreasonsthatcanhappen,noneofwhichImableto
helpdebug. YoulllikelyhavemorelucksearchingGoogleforasolutiontothatissue.

Kenny
July6,2016at7:34amReply

Fact:AnintegerISNOTALWAYSawholenumberalthougheverywholenumberisaninteger
Integers:3,2,1,0,1,2,3
WholeNumbers:0,1,2,3,4

Joel
July21,2016at2:48pmReply

ImusingVisualStudio.
Ivetriedtheoriginalcodeinthelesson

//#include"stdafx.h"//UncommentifVisualStudiouser
#include<iostream>

intmain()
{
//defineanintegervariablenamedx
intx

//printthevalueofxtothescreen(dangerous,becausexisuninitialized)
std::cout<<x

return0
}

Ivetried
//#include"stdafx.h"//UncommentifVisualStudiouser
#include<iostream>

voiddoNothing(constint&x)
{
}

intmain()
{
//declareanintegervariablenamedx
intx

//trickthecompilerintothinkingthisvariableisused
doNothing(x)

//printthevalueofxtothescreen(dangerous,becausexisuninitialized)
std::cout<<x
}

AndIvetriedacoupleofotherthingsfromthecommentssection.

EverythingItryhasthesameresult:
1>Buildstarted:Project:ConsoleApplication1,Configuration:DebugWin32
1>Ataskwascanceled.
1>Ataskwascanceled.
==========Build:0succeeded,1failed,0uptodate,0skipped==========

Halp.

Alex
July22,2016at9:25pmReply

Tryrestartingyourcomputerandseeifthatfixestheissue.

M.Mamdouh
August18,2016at3:40pmReply

[#include<iostream>
usingnamespacestd
intmain()
{

intx
/*inty
cout<<"xvalue"<<endl
cin>>x
cout<<"yvalue"<<endl
cin>>y*/

cout<<x<<endl

system("pause")
return0

}]
notworkinginreleaseconfiguration

Mahesh
November7,2016at3:14amReply

HeyMamdouh,

Outputyourprogramshouldbegarbagevaluebecauseyoucommentedbelowlinesofcode:

/*inty
cout<<"xvalue"<<endl
cin>>x
cout<<"yvalue"<<endl
cin>>y*/

Andwhygarbagevalueisyoudeclaredaintegervariablebutnotinitializedintxandyourprintingout.

PritamDas
September2,2016at11:27pmReply

1 #include <iostream> // finally reckon I am learning some stuff in c++. Thanks to this awesome
2 guy, Alex!
3
4 int main()
5 {
6 using namespace std;
7
8 int a = 5^3;
9 cout << a;
}

Whyisthisprogramprintingthevalue6?Iunderstandthat5^3mightnothavebeenunderstoodbytheIDE/compilerbutit
shouldhavereturnedanerrorthen?Iwonderwhyisitexecutingthevalueas6(inCodeBlocks)

Alex
September4,2016at6:08pmReply

^isntanexponentinC++.InC++,^isabitwiseXOR.Wetalkmoreaboutthis(andhowtodo
exponents)inlesson3.1.

Sanja
September7,2016at4:12pmReply
Hello!Canyoutellmewhichvariablesrequireinitializationandwhichdisallowassignment?Thankyouforcreatingthis
awesomewebsite.

Dekasi
September9,2016at1:50pmReply

AlexIhavethesamedoubtsasSanja(previouscomment).Canyoutelluswhicharethosevariable?

Alex
September9,2016at2:38pmReply

Onlyconstvariablesrequireinitialization(wellcoverconstvariablesinafuturechapter).

Nofundamentalvariablesdisallowassignment,althoughsomecustomtypesdo(wellalsocoverthisinafuturechapter).

Raj
September15,2016at11:26pmReply

#include<iostream>

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

#include<iostream>

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

Whatwillbethememoryuseddifferencebetweentheabovetwoprogram,willitbesameoronewillusemorememorythan
theotherandalsowhatoftheexecutiontime.

Alex
September16,2016at9:18pmReply

Thesetwoprogramswillcompiletoexactlythesamething,andrunexactlythesame.Justthetopone
usesabetterprogrammingstylethanthebottomone.

Mahesh
November7,2016at2:52amReply

Alex,

//defineanintegervariablenamedx
intx

Itsnotdefineaninteger.Itsdeclareandintegervariablenamedx.Pleasecorrectmeifiamwrong.Thanks!

Alex
November7,2016at5:24pmReply

Itsbothadefinitionandadeclaration.Thefactthatitsadefinitionismoreimportant,sincedefinitions
aremorerestrictive.
Mahesh
November7,2016at7:31pmReply

Alex,

intxisjustadeclarationthattellscompilerthatiamgoingtouseavariableinfurtherprogram,butmemoryis
notallocated.Memorywillbeallocatedonlywhenitisinitializedlikeintx=2.Pleasecorrectmeiamwrong
thanks.

Alex
November7,2016at10:54pmReply

Youarewrong.intxdefinesanuninitializedintegervariablenamedx.Memoryisallocatedfor
thevariable,eventhoughitsuninitialized.

Italkmoreaboutthedifferencebetweendeclarationsanddefinitions,andwhenmemoryisallocatedin
futurelessons.

Usman
November24,2016at9:16pmReply

intmain()
{
usingnamespacestd
incomplete

whatdoesusingnamespacestdmeans??

Alex
November25,2016at11:52amReply

Italkaboutthisinlesson4.3cUsingstatementsnow.

Basically,itsashortcuttonothavetotypethestd::prefixsomanytimes.ButIdontrecommendusingit,soI
dontteachituntillateranymore.

You might also like