You are on page 1of 7

Chapter 2 Summary

C++ Basics version 2.0

Identifiers
• Created by the programmer
• Use descriptive names
• Cannot be a reserved word
• case-sensitive
• Start with letter, continue with letters, digits and underscore “_”.

Data Types
The forms of variables used in a program
• bool, 1 bit, true or false; 1 or 0
• char, 8 bits = 1 byte, covers bool
o can hold a small integer –128 .. 127
o usually used to hold an ASCII character
• short, 16 bits = 2 byte, covers all chars
o integer, -32768 .. 32767
• int == long == long int, 32 bits = 4 bytes, covers all shorts
o integer, -2,147,483,648 to 2,147,483,647
• float, 32 bits = 4 bytes
o approx. 10^-38 to 10^38
• double, 64 bits = 8 bytes
o approx. 10^308 to 10^308
o float and double are for real numbers, with fractional parts, also
very large and very small.
o The set of doubles covers the set of floats and ints.

Declaration
data_type variable_name;
• data_type is typically int, double, or short, etc.
• variable_name is an identifier that you make up.
• Every variable must be declared before it’s used.
• Several variables can be declared using commas:
int i1, i2, i3;
• Can initialize in a declaration:
int i1=20, i2=-35, i3=0;
Data Type Conversion
Conversion from a “smaller” to a “larger” data type is usually automatic by the
compiler.
• causes no information loss
• For example, conversion of a char to an int is always exact
Conversion from a “larger” to a “smaller” will generate a compiler complaint,
unless you use a cast or special function to force it.
• there’s information loss, in general
• For example, converting a double to an int will always lose the fractional
part. The double may also be much too large for an int.

Spaces, Tabs and Line feed


• Use freely between identifiers, reserved words and operators.
• You can usually leave them out – the C compiler can usually separate
tokens
• Do not use spaces in identifiers, reserved words or operators.
o This is wrong:
(this price < = that price)
o Write it one of these ways, instead:
(this_price <= that_price)
(this_price<=that_price)
( this_price
<= that_price )

Input/Output
About cout –
• Sends information to the screen or redirected to a file
• Converts data types to character sequences
• Knows all of the above types
• Send a character string like this: cout << “size= “;
• Send “\n” or endl to send a line feed
• Double output can be formatted for precision, showpoint, fixed
• More details in chaper 5
About cin –
• Gets information from the keyboard or file indirection
• Always skips spaces, tabs and line feeds before reading
• Converts input character sequence to appropriate data type
• More details and options in chapter 5
Operators
Arithmetic (use between two numbers)
+ - * / %
• These obey algebraic precedence
• Use (...) to override the precedence rules
• - can be used to negate a number
• % (remainder) can only be used with integers
Assignment (compute the right side, set the left side. Left side: variable)
=
Comparisons (use between two numbers):
< > <= >= == !=
• Don’t write this:
a < b < c
• Write this instead:
(a < b) && (b < c)
Boolean (use between two bools):
&& ||
Boolean complement (use with a single bool):
!
Increment or decrement a variable
++ --
• Must be a variable, not some expression
• This is OK:
++MyVar
• This is WRONG:
(a+b)++
• Can be prefix or postfix.
Shorthand operators (there are more)
+= -= *= /=
Parentheses
( )
• Used to overcome precedence rules – operations inside ( ) is done first
• Parens have other uses in C, as we’ll discover
Statement group
{ }
• Braces are used to group a sequence of statements.
• The statement group can usually replace a statement followed by a
semicolon.
• Each statement in the group must be followed by a semicolon
cout operator
<<
• cout is on the left.
• variables, expressions or strings listed to the right
• use << between pairs of things being printed
• requires #include <iostream>
cin operator
>>
• cin is on the left.
• variables ONLY listed to the right
• use >> between pairs of things being input
• skips blanks, tabs and line feeds before reading input characters
• requires #include <iostream>
Array brackets
[ ]
• Brackets are used with arrays. (see chapter 10)

Flow of Control
How a program is organized – “what happens next”

if – then
if (B) S;

false true
B

• B is a Boolean
• B must be in parentheses
• S; can be { S1; S2; ... Sn; }
• Note: there’s no “then” in this.
• NO semicolon after (B).

if – then – else
if (B) S1; else S2;

false true
B

S2 S1

• there’s no “then”
• “else” must be there
while – do
while (B) S;

false true
B

• Note there’s no “do” in this.


• NO semicolon after (B)

do – while
(note the change – there is no do-until form in C or C++ -- my mistake)
do S; while (B);

true false
B

• In general, don’t use do-while. Use while-do instead.


• do-while always executes S before the test B is made
• subsequent execution of S then depends on B.
• this muddies the logic of a program – maybe S shouldn’t be executed at all!
for loop

for (A; B; C) S;

false true
B

• A is an initialization statement, usually an assignment


• B is a Boolean, used to test for another turn of the loop
• C can be a statement or expression. Use it to increment some variable
• S is a statement. This can be { S1; S2; ... Sn; } instead
• Any of A, B, C can be empty.
• This for loop is equivalent to this short program:
A;
while (B) {
S;
C;
}

Comments
Two styles of comment are provided in C++:
/* a comment that
can extend over many lines
*/

// a comment that extends to the end of this line

• Use comments to describe data variables.


o Add a comment to each variable declaration.
o Try to explain what each variable represents – without this, it’s often very
difficult to tell
• Use comments to describe operations in your program, when they aren’t
very clear
• Use a comment to describe what each function (next chapter) is supposed to
do
Indenting
• Indent source lines between { and }, like this, so that the { and the } line up
vertically:
age= MyAge;
cout << “my age= “ << age << endl;
if (age > 60) {
cout << “...I’m rather old!” << endl;
} else {
cout << “I’m not so old...” << endl;
}
• You can have more {...} inside these, so indent them even more!
• You can use a tab to insert an indent.
• Most text editors will provide “smart indenting”, if they know you are entering C
or C++ code
• Some editors use colors to distinguish identifiers, reserved words, strings and
comments.

Naming Constants
• NEVER just drop a numeric constant into a program, like this:
distance *= 1280;
• Someone else reading this will be puzzled about what the “1280” means. Feet in
a mile?
• INSTEAD, declare constants, like this:
const double PI= 3.14159265; // pi
const int FeetPerMile= 1280; // feet in one
mile
• THEN you can write
distance *= FeetPerMile;

You might also like