How To Troubleshoot Collaboration Apps for the Modern Connected Worker
C++ & VISUAL C++
1. VISUAL C++ PROGRAMMING VC++
SUBJECT: Visual C++ CODE: 710/04/S05
AIMS OF THE SUBJECT
1. To review Object Oriented Program Design and relate it to specific programming languages.
2. To impart the skills to design applications in the VC++ development environment.
3. To impart the skills and knowledge to develop applications that use the fundamental features
of C++, including Classes, Objects, Constructors, Inheritance, encapsulation, overloading etc..
rmmakaha@gmail.com 1
DESIGN LENGTH
THEORY 160 :Hours
LABORATORY 100 :Hours
TOTAL 260 :Hours
SUBJECT OBJECTIVES
The general objective of the units are stated below and the specific objectives of the topic areas
are set out in the syllabus content.
At the end of the course the student should be able to….
1. ..design and implement Visual C++ applications using Object Oriented Programming design
techniques.
2. ..create a Graphical User Interface in the Visual C++ programming environment.
3. ..add code to existing objects and add user defined classes and objects.
4. .. apply basic and more advanced features of Visual C++ in his/her programs, like objects,
classes, inheritance, polymorphism etc..
5. ..develop applications in Visual C++ that incorporate databases and access files.
2. VISUAL C++ PROGRAMMING VC++
Unit 1: Developing applications using the Visual
C++ IDE (100HOURS)
PRACTICAL
This unit is for practical classes. It should complement the other units that are used for
theory classes.
At the end of the unit the student should be able to:
1. ..use the editor, the menus and the application wizard.
2. ..create projects.
3. ..understand and use controls: - General concepts
- Specific controls: e.g. combo box, labels, etc…
4. .. be able to create windows
5. .. understand what events and methods are
6. ..create a simple database application using DAO
7. ..design and implement applications using things like:
- Dialog Boxes
- Mouse events, keyboard events, timers
- Menu’s
- Graphics
8. .. employ the above mentioned things in practical assignments
rmmakaha@gmail.com 2
3. VISUAL C++ PROGRAMMING VC++
Unit 2: Principal Concepts of OOP (10 HOURS)
rmmakaha@gmail.com 3
THEORY
At the end of the unit the student should be able to..
1. .. describe the evolution of software.
2. .. distinguish between procedure-oriented programming and object oriented programming.
3. ..know the Object Oriented Paradigm
3. ..understand basic concepts of Object Oriented Programming.
4. ..mention at least two Object Oriented Programming languages
5. ..mention several applications of Object Oriented Programming.
Distinguish between procedure-oriented programming and object
oriented programming.
Procedure orientated programming is when a programmer creates functions and variables that
are separate parts for his or her program. They may work together but they are distinctly
separated. Object orientated programming is when a programmer takes a concept (an object)
and encapsulates all variables and functions into that concept so that the variables and
functions are distinctly connected. In C++, for example, these objects are called classes. C++
is an extension of the language C along with the capability of creating object classes.
Procedure Oriented Programming
1.Prime focus is on functions and procedures that operate on data
2.Large programs are divided into smaller program units called functions
3.Data and the functions that act upo it are treated as separate entities.
4. Data move freely around the systems from one function to another.
5. Program design follows “Top Down Approach”.
--------------------------------------…
Object Oriented Programming
1.Here more emphasis is laid on the data that is being operated and not the functions or
procedures
2.Programs are divided into what are called objects.
3. Both data and functions are treated together as an integral entity.
4. Data is hidden and cannot be accessed by external functions.
5. Program design follows “Bottom UP Approach”.
4. The OOP Paradigm
VISUAL C++ PROGRAMMING
VC++
Object oriented programming
is a concept that was created because of the need to
overcome the problems that were found with using structured pro
While structured programming uses an approach which is top down, OOP uses an approach
which is bottom up. Traditionally, programming has placed an emphasis on logic and actions.
Object oriented programming has taken a completely diffe
emphasis on objects and information.
broken down into a number of units. These units are called objects. The foundation of OOP is
the fact that it will place an emphasis
Objects will be defined, and they will interact inside the system in a number of different
ways. There are a number of advantages to be found with usin
of these are simple maintenance, an advanced analysis of complicated programs, and
reusability. There are a number of programming languages that use OOP, and some of these
are Java, C++, and Ada. One concept that you will want
modeling. Before you can construct an object oriented system, you will first need to find the
objects within the system and determine the relationships they have. This process is called
data modeling. There are some other OO
A class is a unit that holds data and functions which will carry out operations on the data. A
class will be comprised of three access modifiers. These three modifiers are protected,
private, and public. A member that
designated as private cannot be accessed by objects that exist outside the system. In addition
to this, it cannot be inherited. While a member who is protected can be inherited, they cannot
be accessed by objects which reside outside of the class hierarchy. Another term that you will
hear about often in OOP is objects.
An object is a state of class. It can receive and send messages to other objects, and it can
handle data. The objects which exist w
and will behave in the same manner. There are two things that are found with all objects that
exist in the real world. These two things are behaviors and states. While behaviors and states
are found in real world objects, they can also be found in software objects as well. Another
OOP concept that you will need to know is a method. A method is a process that is used to
handle an object. A method can be public, protected, or private. The visibility of th
will determine how much of it can be seen by outside objects.
Inheritance is an aspect of OOP that allows subclasses to inherit the traits and characteristics
of its superclass. The subclass will inherit all members except those that designated
private. The subclass may have a large number classes from multiple bases, and this concept
is called Multiple Inheritance. It is possible for a subclass to use the behavior of the members
it has inherited, and it can also add new members as well.
that inheritance has, and these are the implementation of abstract data and reusability.
Encapsulation is another important concept that you will need to know. In a nutshell,
encapsulation is responsible for shielding t
only reveal the functional information. However, the implementation will be hidden.
rmmakaha@gmail.com
programming techniques.
different direction, and will place an
With object oriented programming, a problem will be
on objects and classes .
using the OOP paradigm, and some
to become familiar with is data
OOP terms that you will want to know.
is public can be accessed and inherited. A member that is
sed within software are often based off real world objects,
There are two powerful advantages
the data within a class from outside objects. It will
4
gramming rent g P ithin the member
as being
he
5. VISUAL C++ PROGRAMMING VC++
Encapsulation is a concept which promotes modularity, and it is also crucial for hiding
information.
Abstraction is an important concept as well. It allows an application to process objects on a
general level. It is not connected to the instance of an object. It is excellent for locating
patterns that may have a number of different variations. Abstractions are useful because they
can create a common identification that can be found within all their subclasses.
This article serves to demonstrate some of the general concepts of OOP. Object oriented
programming is a paradigm that has created a revolution within the field of computer
programming. If it is used to design programs properly, they will be efficient and easy to
expand and maintain.
Polymorphism
Polymorphism is the ability to apply a standard interface to an object. For example, just about
every electronic device has an on/off switch which performs the same task. The interface to
us is simple and straight forward. What happens inside the electronic device will vary greatly
between devices.
What this means to a C++ programmer is that objects have functions assigned to them, and
similar objects (or derived objects) will implement the same function name to accomplish the
same task, while the mechanics of how it is done may be greatly different.
For example, imaging two objects, one handles input from a keyboard, and the other handles
input from a modem. Both objects implement a function called GetLine. This GetLine
function does the same job from the application viewpoint, it gets a line from an input device.
Our application doesn't have to care if the user is at the keyboard, or across the country via
modem. Chances are that our keyboard object and modem object are both derived from a
standard 'Input' object or base object. All similar objects derived from the Input object would
have to provide the GetLine function.
rmmakaha@gmail.com 5
6. VISUAL C++ PROGRAMMING VC++
Unit 3: Visual C++ basics:
Data types, expressions, control structur
(30 HOURS)
rmmakaha@gmail.com 6
THEORY
At the end of the unit the student should be able to:
1. ..describe what Visual C++ is.
2. ..give examples of applications of C++
3. ..write a simple Visual C++ program
4. ..describe the structure of a Visual C++ program
5. ..use pre-processor directives
6. ..know how to compile and link a source program
7. ..describe what tokens, keywords and identifiers are
8. ..list the basic data types and their characteristics
9. ..create user defined data types and derived data types
10. ..know about compatibility of data types
11. ..be able to declare variables
12. ..employ dynamic initialisation of variables
13. ..know what reference variables are
14. ..list the possible operations in Visual C++
15. ..know the following about operators:
- Scope Resolution Operator
- Member Differencing Operator
- Memory Management Operator
- Manipulators
- operator overloading
- operator precedence
- Type Cast Operator
16. ..know expressions and implicit conversions
17. ..know the control structures of C++ e.g. while, for, if etc..
Your first C++ program
You now know almost enough of the basics to create and compile a program. The program will
use the Standard C++ iostream classes. These read from and write to files and “standard” input
and output (which normally comes from and goes to the console, but may be redirected to files
or devices). In this very simple program, a stream object will be used to print a message on the
screen.
Using the iostreams class
To declare the functions and external data in the iostreams class, include the header file with the
statement
#include <iostream>
7. VISUAL C++ PROGRAMMING VC++
The first program uses the concept of standard output, which means “a general-purpose place to
send output.” You will see other examples using standard output in different ways, but here it
will just go to the console. The iostream package automatically defines a variable (an object)
called cout that accepts all data bound for standard output.
To send data to standard output, you use the operator <<. C programmers know this operator
as the “bitwise left shift,” which will be described in the next chapter. Suffice it to say that a
bitwise left shift has nothing to do with output. However, C++ allows operators to be overloaded.
When you overload an operator, you give it a new meaning when that operator is used with an
object of a particular type. With
iostream objects, the operator << means “send to.” For example:
cout << "howdy!";
sends the string “howdy!” to the object called cout (which is short for “console output”).
That’s enough operator overloading to get you started. Chapter XX covers operator overloading
in detail.
Namespaces
As mentioned in the previous chapter, one of the problems encountered in the C language is that
you “run out of names” for functions and identifiers when your programs reach a certain size.
Of course, you don’t really run out of names – however, it becomes harder to think of new ones
after awhile. More importantly, when a program reaches a certain size it’s typically broken up
into pieces, each of which is built and maintained by a different person or group. Since C
effectively has a single arena where all the identifier and function names live, this means that all
the developers must be careful not to accidentally use the same names in situations where they
can conflict. This rapidly becomes tedious, time-wasting and, ultimately, expensive.
Standard C++ has a mechanism to prevent this collison: the namespace keyword. Each set of
C++ definitions in a library or program is “wrapped” in a namespace, and if some other
definition has an identical name, but is in a different namespace, then there is no collision.
Namespaces are a convenient and helpful tool, but their presence means you must be aware of
them before you can write any programs at all. If you simply include a header file and use some
functions or objects from that header, you’ll probably get strange-sounding errors when you try
to compile the program, to the effect that the compiler cannot find any of the declarations for
the items that you just included in the header file! After you see this message a few times you’ll
become familiar with its meaning (which is: “you included the header file but all the declarations
are within a namespace and you didn’t tell the compiler that you wanted to use the declarations
in that namespace”).
There’s a keyword that allows you to say “I want to use the declarations and/or definitions in
this namespace.” This keyword, appropriately enough, is using. All of the Standard C++
libraries are wrapped in a single namespace, which is std (for “standard”). As this book uses the
standard libraries almost exclusively, you’ll see the following using directive in almost every
program:
using namespace std;
This means that you want to expose all the elements from the namespace called std. After this
statement, you don’t have to worry that your particular library component is inside a namespace,
since the using directive makes that namespace available throughout the file where the using
directive was written.
rmmakaha@gmail.com 7
8. VISUAL C++ PROGRAMMING VC++
Exposing all the elements from a namespace after someone has gone to the trouble to hide them
may seem a bit counterproductive, and in fact you should be careful about thoughtlessly doing
this (as you’ll learn later in the book). However, the using directive only exposes those names
for the current file, so it is not quite so drastic as it first sounds (but think twice about doing it in
a header file – that is reckless).
There’s a relationship between namespaces and the way header files are included. Before the
current header file inclusion style of <iostream> (that is, no trailing ‘ .h’) was standardized, the
typical way to include a header file was with the ‘ .h’, such as <iostream.h>. At that time,
namespaces were not part of the language, either. So to provide backwards compatibility with
existing code, if you say
rmmakaha@gmail.com 8
#include <iostream.h>
It means
#include <iostream>
using namespace std;
However, in this book the standard include format will be used (without the ‘ .h’) and so the
using directive must be explicit.
For now, that’s all you need to know about namespaces, but in Chapter XX the subject is
covered much more thoroughly.
Fundamentals of program structure
A C or C++ program is a collection of variables, function definitions and function calls. When
the program starts, it executes initialization code and calls a special function, “ main( ).” You
put the primary code for the program here.
As mentioned earlier, a function definition consists of a return type (which must be specified in
C++), a function name, an argument list in parentheses, and the function code contained in
braces. Here is a sample function definition:
int function() {
// Function code here (this is a comment)
}
The above function has an empty argument list, and a body that contains only a comment.
There can be many sets of braces within a function definition, but there must always be at least
one set surrounding the function body. Since main( ) is a function, it must follow these rules. In
C++, main( ) always has return type of int.
C and C++ are free form languages. With few exceptions, the compiler ignores newlines and
white space, so it must have some way to determine the end of a statement. Statements are
delimited by semicolons.
C comments start with /* and end with */. They can include newlines. C++ uses C-style
comments and has an additional type of comment: //. The // starts a comment that terminates
with a newline. It is more convenient than /* */ for one-line comments, and is used extensively
in this book.
9. VISUAL C++ PROGRAMMING VC++
rmmakaha@gmail.com 9
"Hello, world!"
And now, finally, the first program:
//: C02:Hello.cpp
// Saying Hello with C++
#include <iostream> // Stream declarations
using namespace std;
int main() {
cout << "Hello, World! I am " << 8 << " Today!" << endl;
} ///:~
The cout object is handed a series of arguments via the ‘ <<’ operators. It prints out these
arguments in left-to-right order. The special iostream function endl outputs the line and a
newline. With iostreams, you can string together a series of arguments like this, which makes the
class easy to use.
In C, text inside double quotes is traditionally called a “string.” However, the Standard C++
library has a powerful class called string for manipulating text, and so I shall use the more
precise term character array for text inside double quotes.
The compiler creates storage for character arrays and stores the ASCII equivalent for each
character in this storage. The compiler automatically terminates this array of characters with an
extra piece of storage containing the value 0, to indicate the end of the character array.
Inside a character array, you can insert special characters by using escape sequences. These consist of
a backslash ( ) followed by a special code. For example n means newline. Your compiler
manual or local C guide gives a complete set of escape sequences; others include t (tab),
(backslash) and b (backspace).
Notice that the entire statement terminates with a semicolon.
Character array arguments and constant numbers are mixed together in the above cout
statement. Because the operator << is overloaded with a variety of meanings when used with
cout, you can send cout a variety of different arguments, and it will “figure out what to do with
the message.”
Throughout this book you’ll notice that the first line of each file will be a comment that starts
with the characters that start a comment (typically //), followed by a colon.
// my first program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
// my first program in C++
10. VISUAL C++ PROGRAMMING VC++
This is a comment line. All lines beginning with two slash signs (//) are considered
comments and do not have any effect on the behavior of the program. The programmer
can use them to include short explanations or observations within the source code itself.
In this case, the line is a brief description of what our program is.
rmmakaha@gmail.com 10
#include <iostream>
Lines beginning with a pound sign (#) are directives for the preprocessor. They are not
regular code lines with expressions but indications for the compiler's preprocessor. In
this case the directive #include <iostream> tells the preprocessor to include the iostream
standard file. This specific file (iostream) includes the declarations of the basic standard
input-output library in C++, and it is included because its functionality is going to be
used later in the program.
using namespace std;
All the elements of the standard C++ library are declared within what is called a
namespace, the namespace with the name std. So in order to access its functionality we
declare with this expression that we will be using these entities. This line is very frequent
in C++ programs that use the standard library, and in fact it will be included in most of
the source codes included in these tutorials.
int main ()
This line corresponds to the beginning of the definition of the main function. The main
function is the point by where all C++ programs start their execution, independently of
its location within the source code. It does not matter whether there are other functions
with other names defined before of after it - the instructions contained within this
function's definition will always be the first ones to be executed in any C++ program.
For that same reason, it is essential that all C++ programs have a main function.
The word main is followed in the code by a pair of parentheses (()). That is because it is a
function declaration: In C++, what differentiates a function declaration from other types
of expressions are these parentheses that follow its name. Optionally, these parentheses
may enclose a list of parameters within them.
Right after these parentheses we can find the body of the main function enclosed in
braces ({}). What is contained within these braces is what the function does when it is
executed.
cout << "Hello World";
This line is a C++ statement. A statement is a simple or compound expression that can
actually produce some effect. In fact, this statement performs the only action that
generates a visible effect in our first program.
cout represents the standard output stream in C++, and the meaning of the entire
statement is to insert a sequence of characters (in this case the Hello World sequence of
characters) into the standard output stream (which usually is the screen).
cout is declared in the iostream standard file within the std namespace, so that's why we
needed to include that specific file and to declare that we were going to use this specific
namespace earlier in our code.
11. VISUAL C++ PROGRAMMING VC++
Notice that the statement ends with a semicolon character (;). This character is used to
mark the end of the statement and in fact it must be included at the end of all expression
statements in all C++ programs (one of the most common syntax errors is indeed to
forget to include some semicolon after a statement).
rmmakaha@gmail.com 11
return 0;
The return statement causes the main function to finish. return may be followed by a
return code (in our example is followed by the return code 0). A return code of 0 for the
main function is generally interpreted as the program worked as expected without any
errors during its execution. This is the most usual way to end a C++ program.
You may have noticed that not all the lines of this program perform actions when the code is
executed. There were lines containing only comments (those beginning by //). There were lines
with directives for the compiler's preprocessor (those beginning by #). Then there were lines
that began the declaration of a function (in this case, the main function) and, finally lines with
statements (like the insertion into cout), which were all included within the block delimited by
the braces ({}) of the main function.
Preprocessor directives (those that begin by #) are out of this general rule since they are not
statements. They are lines read and discarded by the preprocessor and do not produce any code
by themselves. Preprocessor directives must be specified in their own line and do not have to
end with a semicolon (;).
Comments
Comments are parts of the source code disregarded by the compiler. They simply do nothing.
Their purpose is only to allow the programmer to insert notes or descriptions embedded within
the source code.
C++ supports two ways to insert comments:
// line comment
/* block comment */
The first of them, known as line comment, discards everything from where the pair of slash signs
(//) is found up to the end of that same line. The second one, known as block comment,
discards everything between the /* characters and the first appearance of the */ characters, with
the possibility of including more than one line.
12. VISUAL C++ PROGRAMMING VC++
If you include comments within the source code of your programs without using the comment
characters combinations //, /* or */, the compiler will take them as if they were C++
expressions, most likely causing one or several error messages when you compile it.
rmmakaha@gmail.com 12
Variables. Data Types.
Each variable needs an identifier that distinguishes it from the others, for example, in the
previous code the variable identifiers were a, b and result, but we could have called the variables
any names we wanted to invent, as long as they were valid identifiers.
Identifiers
A valid identifier is a sequence of one or more letters, digits or underline characters (_). Neither
spaces nor punctuation marks or symbols can be part of an identifier. Only letters, digits and
underline characters are valid. In addition, variable identifiers always have to begin with a letter.
They can also begin with an underline character (_ ), but this is usually reserved for compiler
specific keywords or external identifiers. In no case they can begin with a digit.
Another rule that you have to consider when inventing your own identifiers is that they cannot
match any keyword of the C++ language or your compiler's specific ones since they could be
confused with these. The standard reserved keywords are:
asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default,
delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for,
friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected,
public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct,
switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned,
using, virtual, void, volatile, wchar_t, while
Additionally, alternative representations for some operators cannot be used as identifiers since
they are reserved words under some circumstances:
and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq
Your compiler may also include some additional specific reserved keywords.
Very important: The C++ language is a "case sensitive" language. That means that an identifier
13. VISUAL C++ PROGRAMMING VC++
written in capital letters is not equivalent to another one with the same name but written in small
letters. Thus, for example, the RESULT variable is not the same as the result variable or the
Result variable. These are three different variable identifiers.
rmmakaha@gmail.com 13
Fundamental data types
When programming, we store the variables in our computer's memory, but the computer has to
know what we want to store in them, since it is not going to occupy the same amount of
memory to store a simple number than to store a single letter or a large number, and they are not
going to be interpreted the same way.
The memory in our computers is organized in bytes. A byte is the minimum amount of memory
that we can manage in C++. A byte can store a relatively small amount of data: one single
character or a small integer (generally an integer between 0 and 255). In addition, the computer
can manipulate more complex data types that come from grouping several bytes, such as long
numbers or non-integer numbers.
Next you have a summary of the basic fundamental data types in C++, as well as the range of
values that can be represented with each one:
Name Description Size* Range*
char Character or small integer. 1byte
signed: -128 to 127
unsigned: 0 to 255
short int
(short)
Short Integer. 2bytes
signed: -32768 to 32767
unsigned: 0 to 65535
int Integer. 4bytes
signed: -2147483648 to
2147483647
unsigned: 0 to 4294967295
long int
(long)
Long integer. 4bytes
signed: -2147483648 to
2147483647
unsigned: 0 to 4294967295
bool
Boolean value. It can take one of two values:
true or false.
1byte true or false
float Floating point number. 4bytes 3.4e +/- 38 (7 digits)
double Double precision floating point number. 8bytes 1.7e +/- 308 (15 digits)
long double Long double precision floating point number. 8bytes 1.7e +/- 308 (15 digits)
wchar_t Wide character. 2bytes 1 wide character
* The values of the columns Size and Range depend on the architecture of the system where the
program is compiled and executed. The values shown above are those found on most 32bit
systems. But for other systems, the general specification is that int has the natural size suggested
by the system architecture (one word) and the four integer types char, short, int and long must
14. VISUAL C++ PROGRAMMING VC++
each one be at least as large as the one preceding it. The same applies to the floating point types
float, double and long double, where each one must provide at least as much precision as the
preceding one.
Introducing strings
While a character array can be fairly useful, it is quite limited. It’s simply a group of characters in
memory, but if you want to do anything with it you must manage all the little details. For
example, the size of a quoted character array is fixed at compile time. If you have a character
array and you want to add some more characters to it, you’ll need to understand quite a lot
(inluding dynamic memory management, character array copying and concatenation) before you
can get your wish. This is exactly the kind of thing we’d like to have an object do for us.
The Standard C++ string class is designed to take care of (and hide) all the low-level
manipulations of character arrays that were previously required of the C++ programmer. These
manipulations have been a constant source of time-wasting and errors since the inception of the
C language. So, although an entire chapter is devoted to the string class later in the book, the
string is so important and it makes life so much easier that it will be introduced here and used in
much of the early part of the book.
To use strings you include the C++ header file <string>. The string class is in the namespace
std so a using directive is necessary. Because of operator overloading, the syntax for using
strings is quite intuitive:
//: C02:HelloStrings.cpp
// The basics of the Standard C++ string class
#include <string>
#include <iostream>
using namespace std;
int main() {
string s1, s2; // Empty strings
string s3 = "Hello, World."; // Initialized
string s4("I am"); // Also initialized
s2 = "Today"; // Assigning to a string
s1 = s3 + " " + s4; // Combining strings
s1 += " 8 "; // Appending to a string
cout << s1 + s2 + "!" << endl;
} ///:~
The first two strings, s1 and s2, start out empty, while s3 and s4 show two equivalent ways to
initialize string objects from character arrays (you can as easily initialize string objects from
other string objects).
You can assign to any string object using ‘ =’. This replaces the previous contents of the string
with whatever is on the right-hand side, and you don’t have to worry about what happens to the
previous contents – that’s handled automatically for you. To combine strings you simply use the
‘ +’ operator, which also allows you to combine character arrays with strings. If you want to
append either a string or a character array to another string, you can use the operator ‘ +=’.
Finally, note that iostreams already know what to do with strings, so you can just send a string
(or an expression that produces a string, which happens with s1 + s2 + "!" ) directly to cout in
order to print it.
rmmakaha@gmail.com 14
15. VISUAL C++ PROGRAMMING
VC++
Variables that can store non-numerical values that are longer than one single character are
known as strings.
The C++ language library provides support for strings through the standard
not a fundamental type, but it behaves in a similar way as fundamental types do in its most basic
usage.
A first difference with fundamental data types is that in order to declare and use objects
(variables) of this type we need to include an addit
and have access to the std namespace (which we already had in all our previous programs thanks
to the using namespace statement).
// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring = "This is a string"
cout << mystring;
return 0;
}
Scope of variables
All the variables that we intend to use in a program must have been declared with its type
specifier in an earlier point in the code, like we did i
body of the function main when we declared that
A variable can be either of global or local scope. A global variable is a variable declared in the
main body of the source code,
the body of a function or a block.
rmmakaha@gmail.com
string
additional header file in our source code:
string";
in the previous code at the beginning of the
a, b, and result were of type
outside all functions, while a local variable is one declared within
15
class. This is
ional <string>
n int.
16. VISUAL C++ PROGRAMMING VC++
Global variables can be referred from anywhere in the code, even inside functions, whenever it is
after its declaration.
The scope of local variables is limited to the block enclosed in braces ({}) where they are
declared. For example, if they are declared at the beginning of the body of a function (like in
function main) their scope is between its declaration point and the end of that function. In the
example above, this means that if another function existed in addition to main, the local variables
declared in main could not be accessed from the other function and vice versa.
rmmakaha@gmail.com 16
Initialization of variables
When declaring a regular local variable, its value is by default undetermined. But you may want a
variable to store a concrete value at the same moment that it is declared. In order to do that, you
can initialize the variable. There are two ways to do this in C++:
The first one, known as c-like, is done by appending an equal sign followed by the value to
which the variable will be initialized:
type identifier = initial_value ;
For example, if we want to declare an int variable called a initialized with a value of 0 at the
moment in which it is declared, we could write:
int a = 0;
The other way to initialize variables, known as constructor initialization, is done by enclosing the
initial value between parentheses (()):
type identifier (initial_value) ;
For example:
int a (0);
Both ways of initializing variables are valid and equivalent in C++.
// initialization of variables
#include <iostream>
17. VISUAL C++ PROGRAMMING VC++
using namespace std;
int main ()
{
int a=5; // initial value = 5
int b(2); // initial value = 2
int result; // initial value undetermined
a = a + 3;
result = a - b;
cout << result;
return 0;
}
6
Specifying storage allocation
When creating a variable, you have a number of options to specify the lifetime of the variable,
how the storage is allocated for that variable, and how the variable is treated by the compiler.
rmmakaha@gmail.com 17
Global variables
Global variables are defined outside all function bodies and are available to all parts of the
program (even code in other files). Global variables are unaffected by scopes and are always
available (i.e., the lifetime of a global variable lasts until the program ends). If the existence of a
global variable in one file is declared using the extern keyword in another file, the data is
available for use by the second file. Here’s an example of the use of global variables:
//: C03:Global.cpp
//{L} Global2
// Demonstration of global variables
#include <iostream>
using namespace std;
int globe;
void func();
int main() {
globe = 12;
cout << globe << endl;
func(); // Modifies globe
cout << globe << endl;
} ///:~
Here’s a file that accesses globe as an extern:
//: C03:Global2.cpp {O}
// Accessing external global variables
extern int globe;
// (The linker resolves the reference)
void func() {
globe = 47;
} ///:~
18. VISUAL C++ PROGRAMMING VC++
Storage for the variable globe is created by the definition in Global.cpp, and that same variable
is accessed by the code in Global2.cpp. Since the code in Global2.cpp is compiled separately
from the code in Global.cpp, the compiler must be informed that the variable exists elsewhere
by the declaration
extern int globe;
When you run the program, you’ll see that the call to func( ) does indeed affect the single global
instance of globe.
In Global.cpp, you can see the special comment tag (which is my own design):
//{L} Global2
This says that to create the final program, the object file with the name Global2 must be linked
in (there is no extension because the extension names of object files differ from one system to
the next). In Global2.cpp, the first line has another special comment tag {O} which says “don’t
try to create an executable out of this file, it’s being compiled so that it can be linked into some
other executable.” The ExtractCode.cpp program at the end of this book reads these tags and
creates the appropriate makefile so everything compiles properly (you’ll learn about makefiles
at the end of this chapter).
rmmakaha@gmail.com 18
Local variables
Local variables occur within a scope; they are “local” to a function. They are often called
automatic variables because they automatically come into being when the scope is entered, and
automatically go away when the scope closes. The keyword auto makes this explicit, but local
variables default to auto so it is never necessary to declare something as an auto.
Register variables
A register variable is a type of local variable. The register keyword tells the compiler “make
accesses to this variable as fast as possible.” Increasing the access speed is implementation
dependent but, as the name suggests, it is often done by placing the variable in a register. There
is no guarantee that the variable will be placed in a register or even that the access speed will
increase. It is a hint to the compiler.
There are restrictions to the use of register variables. You cannot take or compute the address
of a register variable. A register variable can only be declared within a block (you cannot have
global or static register variables). You can, however, use a register variable as a formal
argument in a function (i.e., in the argument list).
Generally, you shouldn’t try to second-guess the compiler’s optimizer, since it will probably do a
better job than you can. Thus, the register keyword is best avoided.
Static
The static keyword has several distinct meanings. Normally, variables defined local to a function
disappear at the end of the function scope. When you call the function again, storage for the
variables is created anew and the values are re-initialized. If you want a value to be extant
19. VISUAL C++ PROGRAMMING VC++
throughout the life of a program, you can define a function’s local variable to be static and give
it an initial value. The initialization is only performed the first time the function is called, and the
data retains its value between function calls. This way, a function can “remember” some piece of
information between function calls.
You may wonder why a global variable isn’t used instead. The beauty of a static variable is that it
is unavailable outside the scope of the function, so it can’t be inadvertently changed. This
localizes errors.
Here’s an example of the use of static variables:
//: C03:Static.cpp
// Using a static variable in a function
#include <iostream>
using namespace std;
rmmakaha@gmail.com 19
void func() {
static int i = 0;
cout << "i = " << ++i << endl;
}
int main() {
for(int x = 0; x < 10; x++)
func();
} ///:~
Each time func( ) is called in the for loop, it prints a different value. If the keyword static is not
used, the value printed will always be ‘1’.
The second meaning of static is related to the first in the “unavailable outside a certain scope”
sense. When static is applied to a function name or to a variable that is outside of all functions,
it means “this name is unavailable outside of this file.” The function name or variable is local to
the file; we say it has file scope. As a demonstration, compiling and linking the following two files
will cause a linker error:
//: C03:FileStatic.cpp
// File scope demonstration. Compiling and
// linking this file with FileStatic2.cpp
// will cause a linker error
// File scope means only available in this file:
static int fs;
int main() {
fs = 1;
} ///:~
Even though the variable fs is claimed to exist as an extern in the following file, the
linker won’t find it because it has been declared static in FileStatic.cpp.
//: C03:FileStatic2.cpp {O}
// Trying to reference fs
extern int fs;
20. VISUAL C++ PROGRAMMING VC++
rmmakaha@gmail.com 20
void func() {
fs = 100;
} ///:~
The static specifier may also be used inside a class. This explanation will be delayed until you
learn to create classes, later in the book.
Extern
The extern keyword has already been briefly described and demonstrated. It tells the compiler
that a variable or a function exists, even if the compiler hasn’t yet seen it in the file currently
being compiled. This variable or function may be defined in another file or further down in the
current file. As an example of the latter:
//: C03:Forward.cpp
// Forward function & data declarations
#include <iostream>
using namespace std;
// This is not actually external, but the
// compiler must be told it exists somewhere:
extern int i;
extern void func();
int main() {
i = 0;
func();
}
int i; // The data definition
void func() {
i++;
cout << i;
} ///:~
When the compiler encounters the declaration ‘ extern int i ’ it knows that the definition for i
must exist somewhere as a global variable. When the compiler reaches the definition of i, no
other declaration is visible so it knows it has found the same i declared earlier in the file. If you
were to define i as static, you would be telling the compiler that i is defined globally (via the
extern), but it also has file scope (via the static), so the compiler will generate an error.
Linkage
To understand the behavior of C and C++ programs, you need to know about linkage. In an
executing program, an identifier is represented by storage in memory that holds a variable or a
compiled function body. Linkage describes this storage it is seen by the linker. There are two
types of linkage: internal linkage and external linkage.
Internal linkage means that storage is created to represent the identifier only for the file being
compiled. Other files may use the same identifier name with internal linkage, or for a global
variable, and no conflicts will be found by the linker – separate storage is created for each
identifier. Internal linkage is specified by the keyword static in C and C++.
21. VISUAL C++ PROGRAMMING VC++
External linkage means that a single piece of storage is created to represent the identifier for all
files being compiled. The storage is created once, and the linker must resolve all other references
to that storage. Global variables and function names have external linkage. These are accessed
from other files by declaring them with the keyword extern. Variables defined outside all
functions (with the exception of const in C++) and function definitions default to external
linkage. You can specifically force them to have internal linkage using the static keyword. You
can explicitly state that an identifier has external linkage by defining it with the extern keyword.
Defining a variable or function with extern is not necessary in C, but it is sometimes necessary
for const in C++.
Automatic (local) variables exist only temporarily, on the stack, while a function is being called.
The linker doesn’t know about automatic variables, and they have no linkage.
rmmakaha@gmail.com 21
Constants
In old (pre-Standard) C, if you wanted to make a constant, you had to use the preprocessor:
#define PI 3.14159
Everywhere you used PI, the value 3.14159 was substituted by the preprocessor (you can still use
this method in C and C++).
When you use the preprocessor to create constants, you place control of those constants outside
the scope of the compiler. No type checking is performed on the name PI and you can’t take the
address of PI (so you can’t pass a pointer or a reference to PI). PI cannot be a variable of a user-defined
type. The meaning of PI lasts from the point it is defined to the end of the file; the
preprocessor doesn’t recognize scoping.
C++ introduces the concept of a named constant that is just like a variable, except its value
cannot be changed. The modifier const tells the compiler that a name represents a constant. Any
data type, built-in or user-defined, may be defined as const. If you define something as const
and then attempt to modify it, the compiler will generate an error.
You must specify the type of a const, like this:
const int x = 10;
In Standard C and C++, you can use a named constant in an argument list, even if the argument
it fills is a pointer or a reference (i.e., you can take the address of a const). A const has a scope,
just like a regular variable, so you can “hide” a const inside a function and be sure that the name
will not affect the rest of the program.
The const was taken from C++ and incorporated into Standard C, albeit quite differently. In C,
the compiler treats a const just like a variable that has a special tag attached that says “don’t
change me.” When you define a const in C, the compiler creates storage for it, so if you define
more than one const with the same name in two different files (or put the definition in a header
file), the linker will generate error messages about conflicts. The intended use of const in C is
quite different from its intended use in C++ (in short, it’s nicer in C++).
22. VISUAL C++ PROGRAMMING VC++
Constant values
In C++, a const must always have an initialization value (in C, this is not true). Constant values
for built-in types are expressed as decimal, octal, hexadecimal, or floating-point numbers (sadly,
binary numbers were not considered important), or as characters.
In the absence of any other clues, the compiler assumes a constant value is a decimal number.
The numbers 47, 0 and 1101 are all treated as decimal numbers.
A constant value with a leading 0 is treated as an octal number (base 8). Base 8 numbers can only
contain digits 0-7; the compiler flags other digits as an error. A legitimate octal number is 017 (15
in base 10).
A constant value with a leading 0x is treated as a hexadecimal number (base 16). Base 16
numbers contain the digits 0-9 and a-f or A-F. A legitimate hexadecimal number is 0x1fe (510 in
base 10).
Floating point numbers can contain decimal points and exponential powers (represented by e,
which means “10 to the power”). Both the decimal point and the e are optional. If you assign a
constant to a floating-point variable, the compiler will take the constant value and convert it to a
floating-point number (this process is one form of what’s called implicit type conversion). However,
it is a good idea to use either a decimal point or an e to remind the reader you are using a
floating-point number; some older compilers also need the hint.
Legitimate floating-point constant values are: 1e4, 1.0001, 47.0, 0.0 and -1.159e-77. You can add
suffixes to force the type of floating-point number: f or F forces a float, L or l forces a long
double, otherwise the number will be a double.
Character constants are characters surrounded by single quotes, as: ‘ A’, ‘ 0’, ‘ ‘. Notice there is a
big difference between the character ‘ 0’ (ASCII 96) and the value 0. Special characters are
represented with the “backslash escape”: ‘ n’ (newline), ‘ t’ (tab), ‘ ’ (backslash), ‘ r’
(carriage return), ‘ "’ (double quotes), ‘ '’ (single quote), etc. You can also express char
constants in octal: ‘ 17’ or hexadecimal: ‘ xff’.
rmmakaha@gmail.com 22
Volatile
Whereas the qualifier const tells the compiler “this never changes” (which allows the compiler to
perform extra optimizations) the qualifier volatile tells the compiler “you never know when this
will change,” and prevents the compiler from performing any optimizations. Use this keyword
when you read some value outside the control of your code, such as a register in a piece of
communication hardware. A volatile variable is always read whenever its value is required, even
if it was just read the line before.
A special case of some storage being “outside the control of your code” is in a multithreaded
program. If you’re watching a particular flag that is modified by another thread or process, that
flag should be volatile so the compiler doesn’t make the assumption that it can optimize away
multiple reads of the flag.
23. VISUAL C++ PROGRAMMING VC++
rmmakaha@gmail.com 23
Constants
Constants are expressions with a fixed value.
Literals
Literals are used to express particular values within the source code of a program. We have
already used these previously to give concrete values to variables or to express messages we
wanted our programs to print out, for example, when we wrote:
a = 5;
the 5 in this piece of code was a literal constant.
Literal constants can be divided in Integer Numerals, Floating-Point Numerals, Characters,
Strings and Boolean Values.
Integer Numerals
1776
707
-273
They are numerical constants that identify integer decimal values. Notice that to express a
numerical constant we do not have to write quotes (") nor any special character. There is no
doubt that it is a constant: whenever we write 1776 in a program, we will be referring to the
value 1776.
In addition to decimal numbers (those that all of us are used to use every day) C++ allows the
use as literal constants of octal numbers (base 8) and hexadecimal numbers (base 16). If we want
to express an octal number we have to precede it with a 0 (zero character). And in order to
express a hexadecimal number we have to precede it with the characters 0x (zero, x). For
example, the following literal constants are all equivalent to each other:
75 // decimal
0113 // octal
0x4b // hexadecimal
24. VISUAL C++ PROGRAMMING VC++
All of these represent the same number: 75 (seventy-five) expressed as a base-10 numeral, octal
numeral and hexadecimal numeral, respectively.
Literal constants, like variables, are considered to have a specific data type. By default, integer
literals are of type int. However, we can force them to either be unsigned by appending the u
character to it, or long by appending l:
rmmakaha@gmail.com 24
75 // int
75u // unsigned int
75l // long
75ul // unsigned long
In both cases, the suffix can be specified using either upper or lowercase letters.
Floating Point Numbers
They express numbers with decimals and/or exponents. They can include either a decimal point,
an e character (that expresses "by ten at the Xth height", where X is an integer value that follows
the e character), or both a decimal point and an e character:
3.14159 // 3.14159
6.02e23 // 6.02 x 1023
1.6e-19 // 1.6 x 10-19
3.0 // 3.0
These are four valid numbers with decimals expressed in C++. The first number is PI, the
second one is the number of Avogadro, the third is the electric charge of an electron (an
extremely small number) -all of them approximated- and the last one is the number three
expressed as a floating-point numeric literal.
The default type for floating point literals is double. If you explicitly want to express a float or
long double numerical literal, you can use the f or l suffixes respectively:
3.14159L // long double
6.02e23f // float
Any of the letters than can be part of a floating-point numerical constant (e, f, l) can be written
using either lower or uppercase letters without any difference in their meanings.
Character and string literals
There also exist non-numerical constants, like:
'z'
25. VISUAL C++ PROGRAMMING VC++
rmmakaha@gmail.com 25
'p'
"Hello world"
"How do you do?"
The first two expressions represent single character constants, and the following two represent
string literals composed of several characters. Notice that to represent a single character we
enclose it between single quotes (') and to express a string (which generally consists of more than
one character) we enclose it between double quotes (").
When writing both single character and string literals, it is necessary to put the quotation marks
surrounding them to distinguish them from possible variable identifiers or reserved keywords.
Notice the difference between these two expressions:
x
'x'
x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single
quotation marks) would refer to the character constant 'x'.
Character and string literals have certain peculiarities, like the escape codes. These are special
characters that are difficult or impossible to express otherwise in the source code of a program,
like newline (n) or tab (t). All of them are preceded by a backslash (). Here you have a list of
some of such escape codes:
n newline
r carriage return
t tab
v vertical tab
b backspace
f form feed (page feed)
a alert (beep)
' single quote (')
" double quote (")
? question mark (?)
backslash ()
26. VISUAL C++ PROGRAMMING VC++
rmmakaha@gmail.com 26
For example:
'n'
't'
"Left t Right"
"onentwonthree"
Additionally, you can express any character by its numerical ASCII code by writing a backslash
character () followed by the ASCII code expressed as an octal (base-8) or hexadecimal (base-16)
number. In the first case (octal) the digits must immediately follow the backslash (for example
23 or 40), in the second case (hexadecimal), an x character must be written before the digits
themselves (for example x20 or x4A).
String literals can extend to more than a single line of code by putting a backslash sign () at the
end of each unfinished line.
"string expressed in
two lines"
You can also concatenate several string constants separating them by one or several blank
spaces, tabulators, newline or any other valid blank character:
"this forms" "a single" "string" "of characters"
Finally, if we want the string literal to be explicitly made of wide characters (wchar_t), instead of
narrow characters (char), we can precede the constant with the L prefix:
L"This is a wide character string"
Wide characters are used mainly to represent non-English or exotic character sets.
Boolean literals
There are only two valid Boolean values: true and false. These can be expressed in C++ as values
of type bool by using the Boolean literals true and false.
Defined constants (#define)
27. VISUAL C++ PROGRAMMING VC++
You can define your own names for constants that you use very often without having to resort
to memory-consuming variables, simply by using the #define preprocessor directive. Its format
is:
rmmakaha@gmail.com 27
#define identifier value
For example:
#define PI 3.14159265
#define NEWLINE 'n'
This defines two new constants: PI and NEWLINE. Once they are defined, you can use them in
the rest of the code as if they were any other regular constant, for example:
// defined constants: calculate circumference
#include <iostream>
using namespace std;
#define PI 3.14159
#define NEWLINE 'n';
int main ()
{
double r=5.0; // radius
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
return 0;
}
31.4159
In fact the only thing that the compiler preprocessor does when it encounters #define directives
is to literally replace any occurrence of their identifier (in the previous example, these were PI
and NEWLINE) by the code to which they have been defined (3.14159265 and 'n'
respectively).
The #define directive is not a C++ statement but a directive for the preprocessor; therefore it
assumes the entire line as the directive and does not require a semicolon (;) at its end. If you
append a semicolon character (;) at the end, it will also be appended in all occurrences within the
body of the program that the preprocessor replaces.
28. VISUAL C++ PROGRAMMING VC++
type typical size description
short 2 bytes stores a short (i.e., small) integer
int 4 bytes stores an integer
long 4 bytes stores a long (i.e., large) integer
float 4 bytes stores a floating-point number
double 8 bytes stores a "double-precision" floating-point number
rmmakaha@gmail.com 28
Declared constants (const)
With the const prefix you can declare constants with a specific type in the same way as you
would do with a variable:
const int pathwidth = 100;
const char tabulator = 't';
const zipcode =12440;
In case that no type is explicitly specified (as in the last example) the compiler assumes that it is
of type int.
String Stream
The standard header file <sstream> defines a class called stringstream that allows a string-based
object to be treated as a stream. This way we can perform extraction or insertion operations
from/to strings, which is especially useful to convert strings to numerical values and vice versa.
For example, if we want to extract an integer from a string we can write:
string mystr ("1204");
int myint;
stringstream(mystr) >> myint;
This declares a string object with a value of "1204", and an int object. Then we use stringstream's
constructor to construct an object of this type from the string object. Because we can use
stringstream objects as if they were streams, we can extract an integer from it as we would have
done on cin by applying the extractor operator (>>) on it followed by a variable of type int.
After this piece of code, the variable myint will contain the numerical value 1204.
// stringstreams
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
29. VISUAL C++ PROGRAMMING VC++
int main ()
{
string mystr;
float price=0;
int quantity=0;
cout << "Enter price: ";
getline (cin,mystr);
stringstream(mystr) >> price;
cout << "Enter quantity: ";
getline (cin,mystr);
stringstream(mystr) >> quantity;
cout << "Total price: " << price*quantity << endl;
return 0;
}
Enter price: 22.25
Enter quantity: 7
Total price: 155.75
In this example, we acquire numeric values from the standard input indirectly. Instead of
extracting numeric values directly from the standard input, we get lines from the standard input
(cin) into a string object (mystr), and then we extract the integer values from this string into a
variable of type int (myint).
Using this method, instead of direct extractions of integer values, we have more control over
what happens with the input of numeric values from the user, since we are separating the
process of obtaining input from the user (we now simply ask for lines) with the interpretation of
that input. Therefore, this method is usually preferred to get numerical values from the user in all
programs that are intensive in user input.
rmmakaha@gmail.com 29
Example
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystr;
30. cout << "What's your name? ";
getline (cin, mystr);
cout << "Hello " << mystr << ".
".n";
cout << "What is your favorite team? ";
getline (cin, mystr);
cout << "I like " << mystr << " too!
return 0;
}
Operators
< too!n";
Booleans: True and False
VC++
Before talking about operators, we'll take a quick aside into
what a boolean is before discussing operators. A boolean value is one that can be either true or
false. No other values are allowed. Booleans and boolean operations are at the heart of
programming. Many times in a program, you'll want to do one thing if a certain
and a different thing if the condition is false. For example, when processing a series of
checkboxes, you may want to take an action only if a box is checked, and do not
That's when you'll want to use a boolean.
Most programming languages have a type for booleans, usually called "boolean" or "bool". Some
C++ compilers recognize the type
supports the bool type. We'll discuss what to do if your compiler doesn't, in a moment.
In order to use boolean logic to your advantage, you need to learn about the three basic boolean
operations. They are called and
inputs, and returns a boolean output. They
shown below.
and
VISUAL C++ PROGRAMMING
rmmakaha@gmail.com
booleans, since we'll need to know
bool, others do not. For now, assume that your compiler
and, or, and not. Each operation takes either one or two boolean
are often represented by symbols known as "gates",
The "and" operation takes two inputs and produces one
output. If both inputs are true, the output is true; in all
other cases, the output is false. It can be interpreted as
follows: "I will return true if input 1 and
30
, condition is true,
nothing otherwise.
, . input 2 are true."
31. or
not
Boolean operators in C++
VISUAL C++ PROGRAMMING
VC++
The "or" operation takes two inputs and produces one
output. If either of the inputs are true, the output is true;
otherwise (i.e., if neither input is true), the output is false. It
can be interpreted as follows: "I will return true if either input 1
or input 2 is true."
The "not" operation takes one input and produces one
output. If the input is true, the output is false. If the input is
false, the output is true. In other words, the "not"
takes the input and returns its opposite.
There are operators in C++ which behave just as the boolean gates shown above! We'll show
you an example of how to use each one.
and: &&
The "and" operator is used by placing
//suppose that Fran is tired
bool franIsTired = true;
the "and" symbol, &&, in between two boolean values.
//but Fran doesn't have to wake up early
bool franMustWakeUpEarly = false;
//will Fran go to sleep now?
bool bedTime = franIsTired &
&& franMustWakeUpEarly;
What does this chunk of code do? It initializes two variables,
franMustWakeUpEarly, to true
including comments!), we determine that Fran will go to sleep
true -- that is, if both inputs to the "and" operation are true. In this case, the first input is true
and the second input is false. Since "and" requires both inputs to be true in order for the output
to be true, but one of the inputs is false, the output will be false. So, the variable
store the value false.
Also, take note that the variable names used here are lengthy. How you decide to program is up
to you, but often times it's better to have lengthie
short, obfuscated variable names like "i" or "zz". (The names in this example may have gone
overboard, though.)
rmmakaha@gmail.com
franIsTired and
and false, respectively. Then, in the third line of code (not
if and only if the "and" operation is
lengthier variable names that are readable, rather than
31
operation
, , bedTime will
r
32. VISUAL C++ PROGRAMMING VC++
rmmakaha@gmail.com 32
or: ||
The "or" operator is used by placing the "or" symbol, ||, in between two boolean values.
//suppose that Graham is tired
bool grahamIsTired = true;
//but Graham doesn't have to wake up early
bool grahamMustWakeUpEarly = false;
//will Graham go to sleep now?
bool bedTime = grahamIsTired || grahamMustWakeUpEarly;
This example is very similar to the example involving Fran, except notice the key difference:
whether or not Graham goes to sleep is determined differently. Graham will go to sleep if he is
tired or if he needs to wake up early. Whereas Fran would go to sleep only if both conditions
were true, Graham will go to sleep if either condition (or both) is true. Therefore, the value of
bedTime is true.
not: !
The "not" operator is used by placing the "not" symbol, !, before a boolean value.
//suppose that Julian stayed up late
bool julianStayedUpLate = true;
//will Julian be peppy tomorrow?
bool julianIsPeppy = !julianStayedUpLate;
This example illustrates the "not" operator. At the end of this block of code, the variable
julianIsPeppy will take on the opposite value of julianStayedUpLate. If julianStayedUpLate were
false, then julianIsPeppy would be true. In this case, the opposite is true, so julianIsPeppy gets a
value of false.
It is perfectly legal in C++ to use boolean operators on variables which are not booleans. In
C++, "0" is false and any non-zero value is true. Let's look at a contrived example.
int hours = 4;
int minutes = 21;
int seconds = 0;
bool timeIsTrue = hours && minutes && seconds;
Since hours evaluates to true, and since minutes evaluates to true, and since seconds evaluates to
false, the entire expression hours && minutes && seconds evaluates to false.
33. VISUAL C++ PROGRAMMING VC++
rmmakaha@gmail.com 33
Arithmetic operators in C++
In addition to the boolean operators, C++ has a number of arithmetic operators. Here they are:
Arithmetic operators
name symbol sample usage
addition + int sum = 4 + 7
subtraction - float difference = 18.55 - 14.21
multiplication * float product = 5 * 3.5
division / int quotient = 14 / 3
modulo ("mod") % int remainder = 10 % 6
They all probably look familiar with the exception of mod (%). The mod is simply the remainder
produced by dividing two integers. In the example shown in the table above, if we treat 10 / 6 as
an integer divison, the quotient is 1 (rather than 1.666) and the remainder is 4. Hence, the
variable remainder will get the value 4.
Equality operators in C++
You are undoubtedly familiar with equality operators, even if you don't know it. An equality
operator is one that tests a condition such as "is less than", "is greater than", and "is equal to".
You will find it useful to be able to compare two numbers using expressions like "x is less than
y".
Let's say you are writing software for a bank ATM (automated teller machine). A customer
makes a request for a certain amount of cash, and your responsibility is to determine if they
should be allowed to withdraw that amount. You could decide to use the following algorithm: "if
the amount requested is less than the account balance, that amount should be withdrawn; otherwise, the customer
should be notified and no money should be withdrawn." Makes sense, right? So, the next step is coming
up with some pseudo-code. Once you have pseudo-code, writing the C++ code will be easy.
Pseudo-code for the ATM problem might look like this:
if the amount requested < account balance then
withdraw the amount requested
otherwise
withdraw nothing and notify the customer
Now that we have pseudo-code, writing the C++ code is as simple as "translating" your pseudo-code
into C++. In this case, it's easy:
if (amountRequested < accountBalance) {
34. VISUAL C++ PROGRAMMING VC++
rmmakaha@gmail.com 34
withdraw(amountRequested);
}
else {
withdraw(0);
notifyCustomer();
}
You'll notice some new syntax in this example, but don't worry about it too much. Pay close
attention to the very first line, which checks to make sure that the amount requested is less than
the account balance. The way it works is, if the expression between parentheses (()) evaluates to
true, then the first block of code will be read. That is, the code inside the first set of curly braces
({}) will be executed. If the expression in parentheses evaluates to false, on the other hand, then
the second block of code (the code following the word else) will be read. In this case, the first
block of code withdraws the amount requested by the customer, while the second block of code
withdraws nothing, and notifies the customer.
That wasn't so hard! All we did was take the original English description of how we would solve
the problem, write some pseudo-code for the English description, and translate the pseudo-code
into C++.
Once you know how to use one equality operator, you know how to use all of them. They all
work the same way: they take the expressions on either side of them, and either return true or
false. Here they are:
Equality operators
name symbol sample usage result
is less than < bool result = (4 < 7) true
is greater than > bool result = (3.1 > 3.1) false
is equal to == bool result = (11 == 8) false
is less than or equal to <= bool result = (41.1 <= 42) true
is greater than or equal to >= bool result = (41.1 >= 42) false
is not equal to != bool result = (12 != 12) false
Assignment operators in C++
Believe it or not, you've already been using assignment operators! Probably the most common
assignment operator is the equals sign (=). It is called "assignment" because you are "assigning" a
variable to a value. This operator takes the expression on its right-hand-side and places it into the
35. VISUAL C++ PROGRAMMING VC++
variable on its left-hand-side. So, when you write x = 5, the operator takes the expression on the
right, 5, and stores it in the variable on the left, x.
Remember how the equality operators, like < and !=, returned a value that indicated the result?
In that case, the return value was either true or false. In fact, almost every expression in C++
returns something! You don't always have to use the return value, though -- it's completely up to
you. In the case of the assignment operators, the return value is simply the value that it stored in
the variable on the left-hand-side.
Sometimes your code will use the return value to do something useful. In the ATM example, one
line of code was executed if the condition was true (that is, if the equality operator returned true).
Two different lines were executed if the condition was false.
Other times, you'll completely ignore the return value, because you're not interested in it. Take a
look at the following code:
int x;
int y;
x = 5;
y = 9;
cout << "The value of x is " << x << endl;
cout << "The value of y is " << y << endl;
int sum;
sum = x + y;
cout << "The sum of x and y is " << sum << endl;
This chunk of code shows why you might want to throw away the return value of an operator.
Look at the third line, x = 5. We're using the assignment operator here to place the value 5 in the
variable x. Since the expression x = 5 returns a value, and we're not using it, then you could say
we are ignoring the return value. However, note that a few of lines down, we are very interested
in the return value of an operator. The addition operator in the expression x + y returns the sum
of its left-hand-side and right-hand-side. That's how we are able to assign a value to sum. You
can think of it as sum = (x + y), since that's what it's really doing.
The other assignment operators are all based on the equals sign, so make sure you understand
that before going on. Here's another assignment operator: +=. How does it work? You might
guess that it has something to do with addition, and something to do with assignment. You'd be
absolutely right! The += operator takes the variable on its left-hand-side and adds the expression
on its right-hand-side. Whenever you see a statement that looks like the following:
rmmakaha@gmail.com 35
36. VISUAL C++ PROGRAMMING VC++
rmmakaha@gmail.com 36
myVar += something;
it is identical to saying the following:
myVar = myVar + something;
That's exactly what it's doing! It's simply a shortcut.
The other common assignment operators are -=, *=, /=, and %=. They all function just like the
+= operator, except instead of adding the value on the right-hand-side, they subtract, or
multiply, or divide, or "mod" it.
Just as the simple assignment operator = returns the value that it stored, all of the assignment
operators return the value stored in the variable on the left-hand-side. Here's an example of how
you might take advantage of this return value. It's not used terribly often, but it can sometimes
be useful.
//these four variables represent the sides of a rectangle
int left;
int top;
int right;
int bottom;
//make it a square whose sides are 4
left = top = right = bottom = 4;
All this code does is store the value in each of the four variables left, top, right, and bottom.
How does it work? It starts on the far right-hand side. It sees bottom = 4. So it places the value
4 in the variable bottom, and returns the value it stored in bottom (which is 4). Since bottom = 4
evaluates to 4, the variable right will also get the value 4, which means top will also get 4, which
means left will also get 4. Phew! Of course, this code could have just as easily been written
//these four variables represent the sides of a rectangle
int left;
int top;
int right;
int bottom;
//make it a square whose sides are 4
left = 4;
top = 4;
right = 4;
bottom = 4;
Operator Precedence
So far, we've seen a number of different operators. Here's a summary of the operators we've
covered so far:
Boolean operators &&, ||, !
37. VISUAL C++ PROGRAMMING VC++
Arithmetic operators +, -, *, /, %
Equality operators <, >, ==, <=, >=, !=
Assignment operators
=, +=, -=, *=, /=,
%=
rmmakaha@gmail.com 37
What is operator precedence?
Operator precedence refers to the order in which operators get used. An operator with high
precedence will get used before an operator with lower precedence. Here's an example:
int result = 4 + 5 * 6 + 2;
What will be the value of result? The answer depends on the precedence of the operators. In C++,
the multiplication operator (*) has higher precedence than the addition operator (+). What that
means is, the multiplication 5 * 6 will take place before either of the additions, so your
expression will resolve to 4 + 30 + 2 , so result will store the value 36.
Since C++ doesn't really care about whitespace, the same thing would be true if you had written:
int result = 4+5 * 6+2;
The result would still be 36.
Maybe you wanted to take the sum 4 + 5 and multiply it by the sum 6 + 2 for a result of 72? Just
as in math class, add parentheses. You can write:
int result = (4 + 5) * (6 + 2);
Operator precedence in C++
Operator precedence in C++ is incredibly easy! Don't let anyone tell you otherwise! Here's the
trick: if you don't know the order of precedence, or you're not sure, add parentheses! Don't even
bother looking it up. We can guarantee that it will be faster for you to add parentheses than to
look it up in this tutorial or in a C++ book. Adding parentheses has another obvious benefit - it
makes your code much easier to read. Chances are, if you are uncertain about the order of
precedence, anyone reading your code will have the same uncertainty.
That having been said, here's the order of operator precedence. In general, the order is what you
would think it is - that is, you can safely say
int x = 4 + 3;
and it will correctly add 4 and 3 before assigning to x. Our advice is to read this table once and
then never refer to it again.
Operator precedence
operators have the same precedence as other operators in their group, and higher precedence than
operators in lower groups
38. VISUAL C++ PROGRAMMING VC++
operator name
! boolean not
* multiplication
/ division
% mod
+ addition
- subtraction
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
&& boolean and
|| boolean or
= assignment
*= multiply and assign
/= divide and assign
%= mod and assign
+= add and assign
-= subtract and assign
Branching Statements (if, else, switch)
rmmakaha@gmail.com 38
The if statement
The first type of branching statement we will look at is the if statement. An if statement has
the form:
if (condition)
{
// code to execute if condition is true
}
else
{
// code to execute if condition is false
}
In an if statement, condition is a value or an expression that is used to determine which code
block is executed, and the curly braces act as "begin" and "end" markers.
Here is a full C++ program as an example:
//include this file for cout
#include <iostream.h>
39. VISUAL C++ PROGRAMMING VC++
rmmakaha@gmail.com 39
int main() {
// define two integers
int x = 3;
int y = 4;
//print out a message telling which is bigger
if (x > y) {
cout << "x is bigger than y" << endl;
}
else {
cout << "x is smaller than y" << endl;
}
return 0;
}
In this case condition is equal to "(x > y)" which is equal to "(3 > 4)" which is a false statement. So
the code within the else clause will be executed. The output of this program will be:
x is smaller than y
If instead the value for x was 6 and the value for y was 2, then condition would be "(6 > 2)" which
is a true statement and the output of the program would be:
x is bigger than y
the switch statement
The next branching statement is called a switch statement. A switch statement is used in place
of many if statements.
Let's consider the following case: Joel is writing a program that figures interest on money that is
held in a bank. The amount of interest that money earns in this bank depends on which type of
account the money is in. There are 6 different types of accounts and they earn interest as follows:
account type interest earned
personal financial 2.3%
personal homeowner 2.6%
personal gold 2.9%
small business 3.3%
big business 3.5%
gold business 3.8%
40. VISUAL C++ PROGRAMMING VC++
One way for Joel to write this program is as follows: (assuming also that Joel has assigned
numbers to the account types starting with personal financial and ending with gold business.)
// declare a variable to keep track of the interest
float interest = 0.0;
// decide which interest rate to use.
if (account_type == 1){
interest = 2.3;
}
else {
rmmakaha@gmail.com 40
if (account_type == 2) {
interest = 2.6;
}
else {
if (account_type == 3){
interest = 2.9;
}
else {
if (account_type == 4){
interest = 3.3;
}
else {
if (account_type == 5){
interest = 3.5;
}
else {
// account type must be 6
interest = 3.8;
}
}
}
}
}
That code is hard to read and hard to understand. There is an easier way to write this, using the
switch statement. The preceding chunk of code could be written as follows:
switch (account_value){
case 1:
interest = 2.3;
break;
case 2:
interest = 2.6;
break;
case 3:
interest = 2.9;
41. VISUAL C++ PROGRAMMING VC++
rmmakaha@gmail.com 41
break;
case 4:
interest = 3.3;
break;
case 5:
interest = 3.5;
break;
case 6:
interest = 3.8;
break;
default:
interest = 0.0;
}
The switch statement allows a programmer to compound a group of if statements, provided
that the condition being tested is an integer. The switch statement has the form:
switch(integer_val){
case val_1:
// code to execute if integer_val is val_1
break;
...
case val_n:
// code to execute if integer_val is val_n
break;
default:
// code to execute if integer_val is none of the above
}
The default clause is optional, but it is good programming practice to use it. The default clause
is executed if none of the other clauses have been executed. For example, if my code looked like:
switch (place) {
case 1:
cout << "we're first" << endl;
break;
case 2:
cout << "we're second" << endl;
break;
default:
cout << "we're not first or second" << endl;
}
42. VISUAL C++ PROGRAMMING VC++
This switch statement will write "we're first" if the variable place is equal to 1, it will write "we're
second" if place is equal to 2, and will write "we're not first or second" if place is any other
value.
The break keyword means "jump out of the switch statement, and do not execute any more
code." To show how this works, examine the following piece of code:
rmmakaha@gmail.com 42
int value = 0;
switch(input){
case 1:
value+=4;
case 2:
value+=3;
case 3:
value+=2;
default:
value++;
}
If input is 1 then 4 will be added to value. Since there is no break statement, the program will go
on to the next line of code which adds 3, then the line of code that adds 2, and then the line of
code that adds 1. So value will be set to 10! The code that was intended was probably:
int value = 0;
switch(input){
case 1:
value+=4;
break;
case 2:
value+=3;
break;
case 3:
value+=2;
break;
default:
value++;
}
This feature of switch statements can sometimes be used to a programmers' advantage. In the
example with the different types of bank accounts, say that the interest earned was a follows:
account type interest earned
personal financial 2.3%
personal homeowner 2.6%
personal gold 2.9%
43. VISUAL C++ PROGRAMMING VC++
small business 2.6%
big business 2.9%
gold business 3.0%
Now, the code for this could be written as:
rmmakaha@gmail.com 43
switch (account_value){
case 1:
interest = 2.3;
break;
case 2:
case 4:
interest = 2.6;
break;
case 3:
case 5:
interest = 2.9;
break;
case 6:
interest = 3.8;
break;
default:
interest = 0.0;
}
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
switch( tolower( *argv[1] ) )
{
// Error. Unreachable declaration.
char szChEntered[] = "Character entered was: ";
case 'a' :
{
// Declaration of szChEntered OK. Local scope.
44. VISUAL C++ PROGRAMMING VC++
char szChEntered[] = "Character entered was: ";
cout << szChEntered << "an"; } break; case 'b' :
rmmakaha@gmail.com 44
// Value of szChEntered undefined.
cout << szChEntered << "bn";
break;
default:
// Value of szChEntered undefined.
cout << szChEntered << "neither a nor bn"; break;
}
}
Control Structures
A program is usually not limited to a linear sequence of instructions. During its process it may
bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that
serve to specify what has to be done by our program, when and under which circumstances.
With the introduction of control structures we are going to have to introduce a new concept: the
compound-statement or block. A block is a group of statements which are separated by semicolons (;)
like all C++ statements, but grouped together in a block enclosed in braces: { }:
{ statement1; statement2; statement3; }
Most of the control structures that we will see in this section require a generic statement as part
of its syntax. A statement can be either a simple statement (a simple instruction ending with a
semicolon) or a compund statement (several instructions grouped in a block), like the one just
described. In the case that we want the statement to be a simple statement, we do not need to
enclose it in braces ({}). But in the case that we want the statement to be a compund statement it
must be enclosed between braces ({}), forming a block.
Conditional structure: if and else
The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is:
if (condition) statement
45. VISUAL C++ PROGRAMMING VC++
Where condition is the expression that is being evaluated. If this condition is true, statement is
executed. If it is false, statement is ignored (not executed) and the program continues right after
this conditional structure.
For example, the following code fragment prints x is 100 only if the value stored in the x variable
is indeed 100:
rmmakaha@gmail.com 45
if (x == 100)
cout << "x is 100";
If we want more than a single statement to be executed in case that the condition is true we can
specify a block using braces { }:
if (x == 100)
{
cout << "x is ";
cout << x;
}
We can additionally specify what we want to happen if the condition is not fulfilled by using the
keyword else. Its form used in conjunction with if is:
if (condition) statement1 else statement2
For example:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it
prints out x is not 100.
The if + else structures can be concatenated with the intention of verifying a range of values.
The following example shows its use telling if the value currently stored in x is positive, negative
or none of them (i.e. zero):
46. VISUAL C++ PROGRAMMING VC++
rmmakaha@gmail.com 46
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";
Remember that in case that we want more than a single statement to be executed, we must group
them in a block by enclosing them in braces { }.
Loops (for, while, do)
Iteration structures (loops)
Loops have as purpose to repeat a statement a certain number of times or while a condition is
fulfilled.
The while loop
Its format is:
while (expression) statement and its functionality is simply to repeat statement while the
condition set in expression is true.
For example, we are going to make a program to countdown using a while-loop:
// custom countdown using while
#include <iostream>
using namespace std;
int main ()
{
int n;
cout << "Enter the starting number > ";
cin >> n;
while (n>0) {
cout << n << ", ";
--n;
}
cout << "FIRE!n";
return 0;
}
Enter the starting number > 8
8, 7, 6, 5, 4, 3, 2, 1, FIRE!
47. VISUAL C++ PROGRAMMING VC++
When the program starts the user is prompted to insert a starting number for the countdown.
Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n is
greater than zero) the block that follows the condition will be executed and repeated while the
condition (n>0) remains being true.
The whole process of the previous program can be interpreted according to the following script
(beginning in main):
1. User assigns a value to n
2. The while condition is checked (n>0). At this point there are two posibilities:
* condition is true: statement is executed (to step 3)
* condition is false: ignore statement and continue after it (to step 5)
rmmakaha@gmail.com 47
3. Execute statement:
cout << n << ", ";
--n;
(prints the value of n on the screen and decreases n by 1)
4. End of block. Return automatically to step 2
5. Continue the program right after the block: print FIRE! and end program.
When creating a while-loop, we must always consider that it has to end at some point, therefore
we must provide within the block some method to force the condition to become false at some
point, otherwise the loop will continue looping forever. In this case we have included --n; that
decreases the value of the variable that is being evaluated in the condition (n) by one - this will
eventually make the condition (n>0) to become false after a certain number of loop iterations: to
be more specific, when n becomes 0, that is where our while-loop and our countdown end.
Of course this is such a simple action for our computer that the whole countdown is performed
instantly without any practical delay between numbers.
The do-while loop
Its format is:
do statement while (condition);
Its functionality is exactly the same as the while loop, except that condition in the do-while loop
is evaluated after the execution of statement instead of before, granting at least one execution of
statement even if condition is never fulfilled. For example, the following example program
echoes any number you enter until you enter 0.
// number echoer
#include <iostream>
using namespace std;
48. VISUAL C++ PROGRAMMING VC++
rmmakaha@gmail.com 48
int main ()
{
unsigned long n;
do {
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "n";
} while (n != 0);
return 0;
}
Enter number (0 to end): 12345
You entered: 12345
Enter number (0 to end): 160277
You entered: 160277
Enter number (0 to end): 0
You entered: 0
The do-while loop is usually used when the condition that has to determine the end of the loop
is determined within the loop statement itself, like in the previous case, where the user input
within the block is what is used to determine if the loop has to end. In fact if you never enter the
value 0 in the previous example you can be prompted for more numbers forever.
The for loop
Its format is:
for (initialization; condition; increase) statement;
and its main function is to repeat statement while condition remains true, like the while loop. But
in addition, the for loop provides specific locations to contain an initialization statement and an
increase statement. So this loop is specially designed to perform a repetitive action with a counter
which is initialized and increased on each iteration.
It works in the following way:
1. initialization is executed. Generally it is an initial value setting for a counter variable. This
is executed only once.
2. condition is checked. If it is true the loop continues, otherwise the loop ends and
statement is skipped (not executed).
3. statement is executed. As usual, it can be either a single statement or a block enclosed in
braces { }.
4. finally, whatever is specified in the increase field is executed and the loop gets back to
step 2.
49. Here is an example of countdown using a for loop:
// countdown using a for loop
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
}
cout << "FIRE!n";
return 0;
}
The initialization and increase fields are optional. They can remain empty, but in all cases the
semicolon signs between them must be written. For example we could write:
wanted to specify no initialization and no increase; or
an increase field but no initialization (maybe because the variable
for (;n<10;n++) if we wanted to include
Optionally, using the comma operator (
fields included in a for loop, like in
expression separator, it serves to separate more than one expression where only one is generally
expected. For example, suppose that we wanted to initialize more than one variable in our loop:
for ( n=0, i=100 ; n!=i ; n++, i
{
// whatever here...
}
This loop will execute for 50 times if neither
n starts with a value of 0, and i
is increased by one and i decreased by one, the loop's condition will become false after t
loop, when both n and i will be equal to
Jump statements.
VISUAL C++ PROGRAMMING
rmmakaha@gmail.com
was already initialized before).
(,) we can specify more than one expression in any of the
initialization, for example. The comma operator (
ves i-- )
r n or i are modified within the loop:
with 100, the condition is n!=i (that n is not equal to
50.
VC++
49
for (;n<10;) if we
) , (,) is an
i). Because n
the 50th
50. VISUAL C++ PROGRAMMING VC++
rmmakaha@gmail.com 50
The break statement
Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to
end an infinite loop, or to force it to end before its natural end. For example, we are going to
stop the count down before its natural end (maybe because of an engine check failure?):
// break loop example
#include <iostream>
using namespace std;
int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}
The continue statement
The continue statement causes the program to skip the rest of the loop in the current iteration as
if the end of the statement block had been reached, causing it to jump to the start of the
following iteration. For example, we are going to skip the number 5 in our countdown:
// continue loop example
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!n";
return 0;
}
The goto statement
goto allows to make an absolute jump to another point in the program. You should use this
feature with caution since its execution causes an unconditional jump ignoring any type of
nesting limitations.
51. VISUAL C++ PROGRAMMING VC++
The destination point is identified by a label, which is then used as an argument for the goto
statement. A label is made of a valid identifier followed by a colon (:).
Generally speaking, this instruction has no concrete use in structured or object oriented
programming aside from those that low-level programming fans may find for it. For example,
here is our countdown loop using goto:
rmmakaha@gmail.com 51
// goto loop example
#include <iostream>
using namespace std;
int main ()
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0) goto loop;
cout << "FIRE!n";
return 0;
}
The exit function
exit is a function defined in the cstdlib library.
The purpose of exit is to terminate the current program with a specific exit code. Its prototype
is:
void exit (int exitcode);
The exitcode is used by some operating systems and may be used by calling programs. By
convention, an exit code of 0 means that the program finished normally and any other value
means that some error or unexpected results happened.
The selective structure: switch.
The syntax of the switch statement is a bit peculiar. Its objective is to check several possible
constant values for an expression. Something similar to what we did at the beginning of this
section with the concatenation of several if and else if instructions. Its form is the following:
switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break;
52. VISUAL C++ PROGRAMMING VC++
rmmakaha@gmail.com 52
.
.
.
default:
default group of statements
}
It works in the following way: switch evaluates expression and checks if it is equivalent to
constant1, if it is, it executes group of statements 1 until it finds the break statement. When it
finds this break statement the program jumps to the end of the switch selective structure.
If expression was not equal to constant1 it will be checked against constant2. If it is equal to this,
it will execute group of statements 2 until a break keyword is found, and then will jump to the
end of the switch selective structure.
Finally, if the value of expression did not match any of the previously specified constants (you
can include as many case labels as values you want to check), the program will execute the
statements included after the default: label, if it exists (since it is optional).
Both of the following code fragments have the same behavior:
switch example if-else equivalent
switch (x) {
case 1:
cout << "x is 1";
break;
case 2:
cout << "x is 2";
break;
default:
cout << "value of x unknown";
}
if (x == 1) {
cout << "x is 1";
}
else if (x == 2) {
cout << "x is 2";
}
else {
cout << "value of x unknown";
}
The switch statement is a bit peculiar within the C++ language because it uses labels instead of
blocks. This forces us to put break statements after the group of statements that we want to be
executed for a specific condition. Otherwise the remainder statements -including those
corresponding to other labels- will also be executed until the end of the switch selective block or
a break statement is reached.
53. VISUAL C++ PROGRAMMING VC++
For example, if we did not include a break statement after the first group for case one, the
program will not automatically jump to the end of the switch selective block and it would
continue executing the rest of statements until it reaches either a break instruction or the end of
the switch selective block. This makes unnecessary to include braces { } surrounding the
statements for each of the cases, and it can also be useful to execute the same block of
instructions for different possible values for the expression being evaluated. For example:
rmmakaha@gmail.com 53
switch (x) {
case 1:
case 2:
case 3:
cout << "x is 1, 2 or 3";
break;
default:
cout << "x is not 1, 2 nor 3";
}
Notice that switch can only be used to compare an expression against constants. Therefore we
cannot put variables as labels (for example case n: where n is a variable) or ranges (case (1..3):)
because they are not valid C++ constants.
If you need to check ranges or values that are not constants, use a concatenation of if and else if
statements.
The for statement
the for statement has the form:
for(initial_value,test_condition,step){
// code to execute inside loop
};
• initial_value sets up the initial value of the loop counter.
• test_condition this is the condition that is tested to see if the loop is executed again.
• step this describes how the counter is changed on each execution of the loop.
Here is an example:
// The following code adds together the numbers 1 through 10
// this variable keeps the running total
int total=0;
// this loop adds the numbers 1 through 10 to the variable total
for (int i=1; i < 11; i++){
total = total + i;
}