Lecture 1 Notes: Introduction: 1.1 Why Use A Language Like C++?
Lecture 1 Notes: Introduction: 1.1 Why Use A Language Like C++?
Lecture 1 Notes: Introduction: 1.1 Why Use A Language Like C++?
At its core, a computer is just a processor with some memory, capable of runnin
instructions like “store 5 in memory location 23459.” Why would we express a progra
a text file in a programming language, instead of writing processor instructions?
The advantages:
1. Conciseness: programming languages allow us to express common sequences of com-
mands more concisely. C++ provides some especially powerful shorthands.
2. Maintainability: modifying code is easier when it entails just a few text edits, instead
of rearranging hundreds of processor instructions. C++object is oriented (more on
that in Lectures 7-8), which further improves maintainability.
3. Portability: di erent processors make di erent instructions available. Programs writ-
ten as text can be translated into instructions for many di erent processors; on
C++’s strengths is that it can be used to write programs for nearly any process
C++ is ahigh-level language: when you write a program in it, the shorthands are su ciently
expressive that you don’t need to worry about the details of processor instructions. C++ does
give access to some lower-level functionality than other languages (e.g. memory addresses).
A program goes from text files (orsource files) to processor instructions as follows:
Compiler
Source File Object File
Linker OS
Executable Program in Memory
Compiler Libraries
Source File Object File
Object files are intermediate files that represent an incomplete copy of the program:
source file only expresses a piece of the program, so when it is compiled into an ob
the object file has some markers indicating which missing pieces it depends on. The
takes those object files and the compiled libraries of predefined code that they rely o
in all the gaps, and spits out the final program, which can then be run by the
system (OS).
The compiler and linker are just regular programs. The step in the compilation process in
which the compiler reads the file is parsingcalled.
In C++, all these steps are performed ahead of time, before you start running a pr
In some languages, they are done during the execution process, which takes time. T
one of the reasons C++ code runs far faster than code in many more recent languag
C++ actually adds an extra step to the compilation process: the code is run thro
preprocessor, which applies some modifications to the source code, before being fed to
compiler. Thus, the modified diagram is:
Preprocessor Compiler
Source File Processed Code Object File
Linker OS
Executable Program in Memory
Preprocessor Compiler Libraries
Source File Processed Code Object File
C++ is immensely popular, particularly for applications that require speed and/or acc
to some low-level features. It was created in 1979 by Bjarne Stroustrup, at first as
of extensions to the C programming language. C++ extends C; our first few lectures
basically be on the C parts of the language.
Though you can write graphical programs in C++, it is much hairier and less portable than
text-based (console) programs. We will be sticking to console programs in this course.
Everything in C++ is case sensitive:someName is not the sameSomeNameas .
2 Hello World
In the tradition of programmers everywhere, we’ll use a “Hello, world!” program as an entry
point into the basic features of C++.
2
4 int main () {
5 std :: cout << " Hello , world !\ n " ;
6
7 return 0;
8 }
2.2 Tokens
Tokens are the minimals chunk of program that have meaning to the compiler – the smallest
meaningful symbols in the language. Our code displays all 6 kinds of tokens, though
usual use of operators is not present here:
Token type Description/Purpose Examples
Keywords Words with special meaning to int, double, for, auto
the compiler
Identifiers Names of things that are cout,n std, x, myFunction
built into the language
Literals Basic constant values whose"Hello, world!", 24.3,
value is specified directly 0,in ’c’
the source code
Operators Mathematical or logical oper+,- -, &&, %, <<
ations
Punctuation/Separators Punctuation defining the { } ( ) , ;
structure of a program
Whitespace Spaces of various sorts; igSpaces,- tabs, newlines, com-
nored by the compiler ments
1. // indicates that everything following it until the end of the line is a comment:
ignored by the compiler. Another way to write a comment is to put it between/* and
*/ (e.g. x = 1 + /*sneaky comment here*/ 1;). A comment of this form may span
multiple lines. Comments exist to explain non-obvious things going on in the co
Use them: document your code well!
2. Lines beginning with# are preprocessor commands, which usually change what code
is actually being compiled#include. tells the preprocessor to dump in the contents of
another file, here theiostream file, which defines the procedures for input/output.
3
4. int main() {...} defines the code that should execute when the program starts up
The curly braces represent grouping of multiple commandsblockinto. Morea about
this syntax in the next few lectures.
5. • cout << : This is the syntax for outputting some piece of text to the scr
We’ll discuss how it works in Lecture 9.
• Namespaces: In C++, identifiers can be defined within a context – sort of
directory of names – callednamespace. When we want to access an identifier
defined in a namespace, we tell the compiler to look for it in that namespace usin
the scope resolution operator(::). Here, we’re telling the compiler to look for
cout in thestd namespace, in which many standard C++ identifiers are defined.
A cleaner alternative is to add the following line below line 2:
using n a m e s p a c e std ;
This line tells the compiler that it should lookstdinnamespacethe for any
identifier we haven’t defined. If we do this, we canstd::omit prefixthe when
writing cout. This is the recommended practice.
• Strings: A sequence of characters suchHello,as world is known as stringa . A
string that is specified explicitly in a programstringis literal.
• Escape sequences: The \n indicates anewline character. It is an example of an
escape sequence– a symbol used to represent a special character in a text lite
Here are all the C++ escape sequences which you can include in strings:
Escape Sequence Represented Character
\a System bell (beep sound)
\b Backspace
\f Formfeed (page break)
\n Newline (line break)
\r “Carriage return” (returns cursor to start of line)
\t Tab
\\Backslash
\’ Single quote character
\" Double quote character
\some integer x The character represented xby
7. return 0 indicates that the program should tell the operating system it has completed
successfully. This syntax will be explained in the context of functions; for now, just include it
as the last line maintheblock.
4
Note that every statement ends with a semicolon (except preprocessor commands and blocks
using {}). Forgetting these semicolons is a common mistake among new C++ programmers.
3.2 Operators
Every expression has a type – a formal description of what kind of data its value
instance, 0 is an integer,3.142 is afloating-point (decimal) number, and"Hello, world!\n"
5
is astring value (a sequence of characters). Data of di erent types take a di erent amounts
of memory to store. Here are the built-in datatypes we will use most often:
Type Names Description Size Range
char Single text character or small1 byte signed: -128 to 127
integer. Indicated with single unsigned: 0 to 255
quotes ’a’(, ’3’).
int Larger integer. 4 bytes signed: -2147483648 to
2147483647
unsigned: 0 to 4294967295
bool Boolean (true/false). Indi-1 byte Just true (1) or false (0).
cated with the keywordstrue
and false.
double “Doubly” precise floating 8 bytes +/- 1.7e +/- 308 ( 15 digits)
point number.
Notes on this table:
• A signed integer is one that can represent a negative number;unsignedaninteger will
never be interpreted as negative, so it can represent a wider range of positive numb
Most compilers assume signed if unspecified.
• There are actually 3 integer types:short, int, andlong, in non-decreasing order of
size (int is usually a synonym for one of the other two). You generally don’t ne
worry about which kind to use unless you’re worried about memory usage or y
using really huge numbers. The same goes for the 3 floating point types,float, double,
and long double, which are in non-decreasing order of precision (there is usually some
imprecision in representing real numbers on a computer).
• The sizes/ranges for each type are not fully standardized; those shown above are
ones used on most 32-bit computers.
An operation can only be performed on compatible types. You34 canand 3add,but you
can’t take the remainder of an integer and a floating-point number.
An operator also normally produces a value of the same type as its operands;1/4 thus,
evaluates to0 because with two integer operands,/truncates the result to an integer. To
get 0.25, you’d need to write something1 / like4.0 .
A text string, for reasons we will learn in Lecture 5, haschar the*. type
6
4 Variables
We might want to give a value a name so we can refer to it later. Wevariablesdo.this using
A variable is a named location in memory.
For example, say we wanted to use the4 +value2multiple times. We might callx andit
use it as follows:
1 # include < iostream >
2 using n a m e s p a c e std ;
3
4 int main () {
5 int x ;
6 x = 4 + 2;
7 cout << x / 3 << ’ ’ << x * 2;
8
9 return 0;
10 }
5 Input
Now that we know how to give names to values, we can have the user of the progr
values. This is demonstrated in line 6 below:
7
1 # include < iostream >
2 using n a m e s p a c e std ;
3
4 int main () {
5 int x ;
6 cin >> x ;
7
8 cout << x / 3 << ’ ’ << x * 2;
9
10 return 0;
11 }
Just as cout << is the syntax for outputting values,cin >> (line 6) is the syntax for
inputting values.
Memory trick: if you have trouble remembering which way the angle brackets gocoutfor
and cin, think of them as arrows pointing in the direction ofcindatarepresentsflow. the
terminal, with data flowing from it to your variabcoutlikewisees; represents the terminal,
and your data flows to it.
6 Debugging
There are two kinds of errors you’ll run into when writing C++compilationprograms:
errors and runtime errors. Compilation errors are problems raised by the compiler, generally
resulting from violations of the syntax rules or misuse of types. These are often caus
typos and the like. Runtime errors are problems that you only spot when you ru
program: you did specify a legal program, but it doesn’t do what you wanted it to.
are usually more tricky to catch, since the compiler won’t tell you about them.
8
MIT OpenCourseWare
http://ocw.mit.edu
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.