You are on page 1of 9

6.

096
IntroductiontoC++ January4,2011
MassachusettsInstituteofTechnology
Lecture 1 Notes: Introduction
1 Compiled Languages and C++
1.1 Why Use a Language Like C++?
Atitscore,acomputerisjustaprocessorwithsomememory,capableofrunningtiny
instructionslikestore5inmemorylocation23459.Whywouldweexpressaprogramas
atextleinaprogramminglanguage,insteadofwritingprocessorinstructions?
Theadvantages:
1.Conciseness: programminglanguagesallowustoexpresscommonsequencesofcom-
mandsmoreconcisely.C++providessomeespeciallypowerfulshorthands.
2.Maintainability: modifyingcode is easier when itentails justa few textedits, instead
ofrearranginghundredsofprocessorinstructions. C++isobject oriented (moreon
thatinLectures7-8),whichfurtherimprovesmaintainability.
3.Portability: dierent processors make dierent instructions available.Programs writ-
tenastextcanbetranslatedintoinstructionsformanydierentprocessors;oneof
C++sstrengthsisthatitcanbeusedtowriteprogramsfornearlyanyprocessor.
C++ is a high-level language:when you write a program in it, the shorthands are suciently
expressive that you dontneed to worryabout the details of processor instructions.C++does
give access to some lower-level functionalitythan other languages (e.g.memoryaddresses).
1.2 The Compilation Process
A program goes from textles (orsource les) toprocessorinstructionsasfollows:
Source File Object File
Compiler
Source File Object File
Compiler
Execut abl e
Linker
Libraries
Program i n Memory
OS
Objectlesareintermediatelesthatrepresentanincompletecopyoftheprogram:each
sourceleonlyexpressesapieceoftheprogram,sowhenitiscompiledintoanobjectle,
theobjectlehassomemarkersindicatingwhichmissingpiecesitdependson.Thelinker
takesthoseobjectlesandthecompiledlibrariesofpredenedcodethattheyrelyon,lls
inallthegaps,andspitsoutthenalprogram,whichcanthenberunbytheoperating
system (OS).
Thecompilerand linkerare justregular programs.Thestep in thecompilation process in
whichthecompilerreadstheleiscalledparsing.
InC++,allthesestepsareperformedaheadoftime,beforeyoustartrunningaprogram.
Insomelanguages,theyaredoneduringtheexecutionprocess,whichtakestime.Thisis
oneofthereasonsC++coderunsfarfasterthancodeinmanymorerecentlanguages.
C++actuallyaddsanextrasteptothecompilationprocess:thecodeisrunthrougha
preprocessor,whichappliessomemodicationstothesourcecode,beforebeingfedtothe
compiler.Thus,themodieddiagramis:
Source File Processed Code
Preprocessor
Object File
Compiler
Source File Processed Code
Preprocessor
Object File
Compiler
Execut abl e
Linker
Libraries
OS
Program i n Memory
1.3 General Notes on C++
C++isimmenselypopular,particularlyforapplicationsthatrequirespeedand/oraccess
tosomelow-levelfeatures. Itwascreatedin1979byBjarneStroustrup,atrstasaset
ofextensionstotheCprogramminglanguage.C++extendsC;ourrstfewlectureswill
basicallybeontheCpartsofthelanguage.
Though youcanwrite graphical programs in C++, it ismuch hairierand less portable than
text-based (console) programs.Wewillbestickingtoconsoleprogramsinthiscourse.
EverythinginC++iscasesensitive:someNameisnotthesameasSomeName.
2 Hello World
In the tradition of programmers everywhere, welluse aHello, world!program as an entry
pointintothebasicfeaturesofC++.
2.1 The code
1
2
3
// A Hello World program
#include <iostream>
2
4 int main() {
5 std::cout << "Hello , world!\n";
6
7 return 0;
8 }
2.2 Tokens
Tokens are the minimals chunkof program that have meaningto the compiler the smallest
meaningfulsymbolsinthelanguage. Ourcodedisplaysall6kindsoftokens,thoughthe
usualuseofoperatorsisnotpresenthere:
Token type Description/Purpose Examples
Keywords Wordswith specialmeaning to
thecompiler
int, double, for, auto
Identiers Namesofthingsthatarenot
builtintothelanguage
cout, std, x, myFunction
Literals Basicconstantvalueswhose
valueisspecieddirectlyin
thesourcecode
"Hello, world!", 24.3,
0, c
Operators Mathematicalorlogicaloper-
ations
+, -, &&, %, <<
Punctuation/Separators Punctuation dening the
structureofaprogram
{}( ) , ;
Whitespace Spaces of various sorts; ig-
noredbythecompiler
Spaces,tabs,newlines,com-
ments
2.3 Line-By-Line Explanation
1.// indicatesthateverythingfollowingituntiltheendofthelineisacomment:itis
ignored bythe compiler.Another wayto write a comment is to put it between/*and
*/(e.g.x = 1 + /*sneaky comment here*/ 1;).Acommentofthisformmayspan
multiplelines. Commentsexisttoexplainnon-obviousthingsgoingoninthecode.
Usethem:documentyourcodewell!
2.Linesbeginningwith# arepreprocessorcommands,whichusuallychangewhatcode
is actually beingcompiled.#includetells the preprocessor to dump in the contents of
anotherle,heretheiostreamle,whichdenestheproceduresforinput/output.
3
4.int main() {...} denesthecodethatshouldexecutewhentheprogramstartsup.
Thecurlybracesrepresentgroupingofmultiplecommandsintoablock.Moreabout
thissyntaxinthenextfewlectures.
5. cout << : Thisisthesyntaxforoutputtingsomepieceoftexttothescreen.
WelldiscusshowitworksinLecture9.
Namespaces: InC++,identierscanbedenedwithinacontextsortofa
directoryofnamescalledanamespace.Whenwewanttoaccessanidentier
dened in a namespace, we tellthe compiler to look for it in thatnamespace using
thescope resolution operator (::). Here,weretellingthecompilertolookfor
coutin thestdnamespace, in whichmanystandard C++ identiers are dened.
Acleaneralternativeistoaddthefollowinglinebelowline2:
using namespace std;
Thislinetellsthecompilerthatitshouldlookinthestd namespaceforany
identierwehaventdened.Ifwedothis,wecanomitthestd:: prexwhen
writingcout.Thisistherecommendedpractice.
Strings: A sequence ofcharacters suchasHello, worldis known as astring. A
stringthatisspeciedexplicitlyinaprogramisastring literal.
Escapesequences: The\nindicates anewline character.It is an example ofan
escape sequence asymbolusedtorepresentaspecialcharacterinatextliteral.
HerearealltheC++escapesequenceswhichyoucanincludeinstrings:
Escape Sequence Represented Character
\a Systembell(beepsound)
\b Backspace
\f Formfeed(pagebreak)
\n Newline(linebreak)
\r Carriagereturn(returnscursortostartofline)
\t Tab
\\ Backslash
\ Singlequotecharacter
\" Doublequotecharacter
\some integer x Thecharacterrepresentedbyx
7.return 0indicates that the program shouldtellthe operatingsystem it has completed
successfully.This syntaxwill be explained in the contextof functions; for now, just
includeitasthelastlineinthemain block.
4
Note thateverystatementends witha semicolon (except preprocessor commands and blocks
using{}).Forgettingthese semicolons is a common mistake amongnew C++ programmers.
3 Basic Language Features
Sofarourprogramdoesntdoverymuch.Letstweakitinvariouswaystodemonstrate
somemoreinterestingconstructs.
3.1 Values and Statements
First,afewdenitions:
A statement is a unit ofcode that does something a basic building blockofa program.
Anexpression isastatementthathasavalue forinstance,anumber,astring,the
sumoftwonumbers,etc.4 + 2,x - 1,and"Hello, world!\n"areallexpressions.
Noteverystatementisanexpression. Itmakesnosensetotalkaboutthevalueofan
#includestatement, for instance.
3.2 Operators
We can perform arithmetic calculations withoperators. Operators acton expressions to form
anewexpression.Forexample,wecouldreplace"Hello, world!\n" with(4 + 2) / 3,
whichwouldcausetheprogramtoprintthenumber2.Inthiscase,the+ operatoractson
theexpressions4 and2 (its operands).
Operator types:
Mathematical: +,-,*,/,andparentheseshavetheirusualmathematicalmeanings,
includingusing- fornegation.% (themodulus operator)takestheremainderoftwo
numbers:6 % 5 evaluates to 1.
Logical: usedforand,or,andsoon.Moreonthoseinthenextlecture.
Bitwise: usedto manipulate the binaryrepresentations ofnumbers.We willnot focus
on these.
3.3 Data Types
Everyexpressionhasatypeaformaldescriptionofwhatkindofdataitsvalueis.For
instance, 0is an integer, 3.142is a oating-point (decimal) number, and"Hello, world!\n"
5
isastring value (asequenceofcharacters).Dataof dierent types takea dierentamounts
ofmemorytostore.Herearethebuilt-indatatypeswewillusemostoften:
Type Names Description Size Range
char Singletextcharacterorsmall
integer.Indicatedwithsingle
quotes(a,3).
1byte signed:-128to127
unsigned:0to255
int Largerinteger. 4bytes signed: -2147483648 to
2147483647
unsigned:0to4294967295
bool Boolean (true/false). Indi-
catedwiththekeywordstrue
andfalse.
1byte Justtrue (1) orfalse (0).
double Doubly precise oating
pointnumber.
8bytes +/- 1.7e+/- 308(15digits)
Notesonthistable:
Asigned integerisonethatcanrepresentanegativenumber;anunsigned integerwill
never be interpretedas negative, so itcan representa wider range of positive numbers.
Mostcompilersassumesignedifunspecied.
Thereareactually3integertypes:short,int,andlong,innon-decreasingorderof
size (int isusuallyasynonymforoneoftheothertwo).Yougenerallydontneedto
worryaboutwhichkindtouseunlessyoureworriedaboutmemoryusageoryoure
usingreally huge numbers.The same goes for the 3 oating point types, float,double,
andlong double, whichare in non-decreasingorder of precision (there is usuallysome
imprecisioninrepresentingrealnumbersonacomputer).
Thesizes/rangesforeachtypearenotfullystandardized;thoseshownabovearethe
onesusedonmost32-bitcomputers.
Anoperationcanonlybeperformedoncompatibletypes.Youcanadd34 and3, but you
canttaketheremainderofanintegerandaoating-pointnumber.
Anoperatoralsonormallyproducesavalueofthesametypeasitsoperands;thus,1 / 4
evaluates to0 becausewithtwointegeroperands,/ truncatestheresulttoaninteger.To
get0.25,youdneedtowritesomethinglike1 / 4.0.
Atextstring,forreasonswewilllearninLecture5,hasthetypechar *.
6
4 Variables
We mightwant to give a value a name so we can refer to it later.We do this usingvariables.
Avariableisanamedlocationinmemory.
Forexample,saywewantedtousethevalue4 + 2 multipletimes.Wemightcallitx and
useitasfollows:
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5 int x;
6 x = 4 + 2;
7 cout << x / 3 << << x * 2;
8
9 return 0;
10 }
(Notehowwecanprintasequenceof valuesbychainingthe<< symbol.)
Thenameofavariableisanidentiertoken.Identiersmaycontainnumbers,letters,and
underscores (),and maynotstartwithanumber.
Line4isthedeclaration ofthevariablex.Wemusttellthecompilerwhattypex will be
sothatitknowshowmuchmemorytoreserveforitandwhatkindsofoperationsmaybe
performedonit.
Line5istheinitialization ofx,wherewespecifyaninitialvalueforit.Thisintroducesa
newoperator:=,theassignmentoperator.Wecanalsochangethevalueofxlateroninthe
codeusingthisoperator.
Wecouldreplacelines4and5withasinglestatementthatdoesbothdeclarationand
initialization:
int x = 4 + 2;
Thisformofdeclaration/initializationiscleaner,soitistobepreferred.
5 Input
Nowthatweknowhowtogivenamestovalues,wecanhavetheuseroftheprograminput
values.This is demonstrated in line 6 below:
7
1 #include <iostream>
2 using namespace std;
3
4 int main() {
5 int x;
6 cin >> x;
7
8 cout << x / 3 << << x * 2;
9
10 return 0;
11 }
Just ascout <<is the syntax for outputting values,cin >>(line 6) is the syntax for inputting
values.
Memory trick: if you have troublerememberingwhichwaytheangle brackets go forcout
andcin,thinkofthemasarrowspointinginthedirectionofdataow.cin represents the
terminal,withdataowingfromittoyourvariables;coutlikewiserepresentstheterminal,
andyourdataowstoit.
6 Debugging
TherearetwokindsoferrorsyoullrunintowhenwritingC++programs: compilation
errors andruntime errors. Compilation errors are problems raised by the compiler, generally
resultingfromviolationsofthesyntaxrulesormisuseoftypes.Theseareoftencausedby
typosandthelike. Runtimeerrorsareproblemsthatyouonlyspotwhenyourunthe
program:youdidspecifyalegalprogram,butitdoesntdowhatyouwanteditto.These
areusuallymoretrickytocatch,sincethecompilerwonttellyouaboutthem.
8
MIT OpenCourseWare
http://ocw.mit.edu
6.096 Introduction to C++
January (IAP) 2011
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.

You might also like