C++ Basics Part 1
C++ Basics Part 1
C++ Basics Part 1
4. Run it!
Variables
Variables are used to store data. Every C++ variable has a:
Name -- chosen by the programmer (aka identifier)
Type -- specified in the declaration of the variable
Size -- determined by the type
Value -- the data stored in the variable's memory location
Address -- the starting location in memory where the value is stored
When a program is compiled, a symbol table is created, mapping each variable name to its type,
size, and address
Identifiers
Identifiers are the names for things (variables, functions, etc) in the language. Some identifiers are
built-in, and others can be created by the programmer.
User-defined identifiers can consist of letters, digits, and underscores
Must start with a non-digit
Identifiers are case sensitive (count and Count are different variables)
Reserved words (keywords) cannot be used as identifiers
A list of reserved keywords in C++ can be found on page 43 in the textbook
// good
// bad
Declaring Variables
Declare Before Use: Variables must be declared before they can be used in any other
statements
float
double
long double
Sizes
Sizes for these types are implementation dependent
numerical types above listed in smallest to largest order
can use built-in sizeof() function to find out sizes of types or variables for a system
For most computers today: char typically 1 byte; int typically 4 bytes
This program will print the number of bytes used by each type - sizes may vary from system to
system
Initializing Variables
To declare a variable is to tell the compiler it exists, and to reserve memory for it
Variables of built-in types can be declared and initialized on the same line, as well
int numStudents = 10;
double weight = 160.35;
char letter = 'A';
int test1 = 96, test2 = 83, finalExam = 91;
double x = 1.2, y = 2.4, z = 12.9;
Constant Variables
(Woohoo! An oxymoron!)
A variable can be declared to be constant. This means it cannot change once it's declared and
initialized
Use the keyword const
MUST declare and initialize on the same line
const int SIZE = 10;
const double PI = 3.1415;
// this one is illegal, because it's not
// initialized on the same line
const int LIMIT; // BAD!!!
LIMIT = 20;
The preprocessor replaces all occurrences of the symbol in code with the value following it.
(like find/replace in MS Word). This happens before the actual compilation stage begins
Questions to consider
What's the difference between these?
#define SIZE 10
const int SIZE = 10;
Why use a constant variable (or symbolic constant)? i.e. what's the advantage?
When is use of a constant a good idea? When is it not worthwhile?
floating point literal -- an actual decimal number written in code (4.5, -12.9, 5.0)
Note: these are interpreted as type double by standard C++ compilers
Can also be written in exponential (scientific) notation: (3.12e5, 1.23e-10)
character literal -- a character in single quotes: ('F', 'a', '\n')
string literal -- a string in double quotes: ("Hello", "Bye", "Wow!\n")
Escape Sequences
String and character literals can contain special escape sequences
They represent single characters that cannot be represented with a single character from the
keyboard in your code
The backslash \ is the indicator of an escape sequence. The backslash and the next character
are together considered ONE item (one char)
Some common escape sequences are listed in the table below
Escape
Sequence
Meaning
\n
newline
\t
tab
\r
carriage return
\a
alert sound
\"
double quote
\'
single quote
\\
backslash
Comments
Comments are for documenting programs. They are ignored by the compiler.
Block style (like C)
/* This is a comment.
It can span multiple lines */
output stream
Of class type ostream (to be discussed later)
Usually defaults to the monitor
cin -- standard input stream
Of class type istream (to be discussed later)
Usually defaults to the keyboard
cerr -- standard error stream
Of class type ostream
Usually defaults to the monitor, but allows error messages to be directed elsewhere (like
a log file) than normal output
To use these streams, we need to include the iostream library into our programs.
#include <iostream>
using namespace std;
The using statement tells the compiler that all uses of these names (cout, cin, etc) will come from the
"standard" namespace.
Using Input and Output Streams
output streams are frequently used with the insertion operator <<
Format: outputStreamDestination << itemToBePrinted
The right side of the insertion operator can be a variable, a constant, a value, or the result
of a computation or operation
Examples:
cout << "Hello World"; // print a string literal
cout << 'a'; // print a character literal
cout << numStudents; // print contents of a variable
cout << x + y - z; // print result of a computation
cerr << "Error occurred"; // string literal printed to standard error
When printing multiple items, the insertion operator can be "cascaded". Place another
operator after an output item to insert a new output item:
cout << "Average = " << avg << '\n';
cout << var1 << '\t' << var2 << '\t' << var3;
input streams are frequently used with the extraction operator >>
Format: inputStreamSource >> locationToStoreData
The right side of the extraction operator MUST be a memory location. For now, this
means a single variable!
By default, all built-in versions of the extraction operator will ignore any leading "whitespace" characters (spaces, tabs, newlines, etc)
Examples:
int numStudents;
cin >> numStudents; // read an integer
double weight;
cin >> weight; // read a double
cin >> '\n'; // ILLEGAL. Right side must be a variable
cin >> x + y; // ILLEGAL. x + y is a computation, not a variable
A special "magic formula" for controlling how many decimal places are printed:
cout.setf(ios::fixed); // specifies fixed point notation
cout.setf(ios::showpoint); // so that decimal point will always be shown
cout.precision(2); // sets floating point types to print to
// 2 decimal places (or use your desired number)
Any cout statements following these will output floating-point values in the usual notation, to 2
decimal places.
double x = 4.5, y = 12.666666666666, z = 5.0;
cout << x; // prints 4.50
cout << y; // prints 12.67
cout << z; // prints 5.00
These statements use what are called stream manipulators, which are symbols defined in the
iostream