You are on page 1of 34

Chapter V

Variables and Constants

Chapter V Topics
5.1 Introduction

5.2 Defining and Assigning Variables

5.3 Mixing Data Types

5.4 Initialized Variables

5.5 Program Sequence

5.6 String Variables

5.7 Program Constants

Chapter V Variables and Constants 5.1


5.1 Introduction

In the early days of your mathematics classes only constants were used. You
know, numbers like 5, 13 and 127. You added, subtracted, multiplied and divided
with numbers. Later, you had more fun with fractions and decimal numbers. At
some point - the exact year does not matter - variables were introduced. In
science and mathematics it is useful to express formulas and certain relationships
with variables that explain some general principle. If you drive at an average rate
of 60 mph and you continue for 5 hours at that rate, you will cover 300 miles.
On the other hand, if you drive at a rate of 45mph for 4 hours, you will travel 180
miles. These two problems are examples that only use constants. The method
used for computing this type of problem can be expressed in a more general
formula that states:
Distance = Rate  Time

The formula is normally used in its abbreviated form, which is D = R  T. In


this formula D, R and T are variables. The meaning is literal. A variable is a
value that is able to change. A constant like 5 will always be 5, but D is a
variable, which changes with the values of R and T. Both R and T are also
variables. Variables make mathematics, science and computer science possible.
Without variables you are very limited in the type of programs that you can write.
Consider how limited program PROG0501.CPP is, which uses only constant
values.

// PROG0501.CPP
// This program demonstrates using four constants.

#include <iostream.h>
#include <conio.h>

void main()
{
clrscr();
cout << 2500 << endl;
cout << 123.4567 << endl;
cout << 'M' << endl;
cout << "Howdy Neighbors" << endl;
getch();
}

This program uses an integer constant, 2500, a real number constant, 123.4567,
a chararacter constant M, and a string constant Howdy Neighbors. In this

Chapter V Variables and Constants 5.2


chapter we will look at a variety of programs that use integers, real numbers,
characters, and string variables.
5.2 Defining and Assigning Variables

In an earlier chapter, I explained how information is stored in binary code. The


letter, or character A is given the code 65, which is 01000001 in base 2. One byte
of computer memory is used to store this one character, which is represented by
an 8-BIT number. Storing a 20-character name will require 20 bytes of memory.
Different types of values have different memory requirements. A computer
program, which includes compilers, is normally designed to handle computer
memory as efficiently as possible. This means that a computer program, with a
modern language like C++, needs some method to indicate the memory
requirements for its variables.

It may seem easy to allow the same space for every type of value stored in a
program, but this is very impractical and can cause all sorts of problems. Imagine
that your school decides that every classroom will be precisely the same size with
every room sized for 30 desks. This may sound like a fine solution but there will
be problems. Special education classes are normally very small and do not
require space for 30 desks. Band and orchestra classes are frequently
considerably larger than 30 students and would not fit. Computer labs may be
designed for 30 students, but the space required for 30 computers and 30 students
will not fit in a classroom designed for only 30 desks. The solution used by most
schools is to consider the needs of the class and find an appropriate room.

The “space efficiency” issue is the biggest reason why it is necessary to let the
compiler know how many variables, and what type of variables will be used in a
program. With the proper variable information, the compiler is able to allocate
the necessary memory for correct execution of the program.

Are you tired of this memory stuff? Probably, and frankly I prefer showing some
program examples and let you see what is happening in the syntax department.
The general rule for a variable definition is to start with the C++ data type and
follow it with the variable name. Usually, we call the name of a variable the
identifier. An identifier is composed of alpha-numeric characters and the
under_score character. All identifiers must start with a letter.

Variable Definition Syntax

datatype Variable Identifier // optional but desired comment


int Number;
char Choice;

Chapter V Variables and Constants 5.3


Take a look at PROG0502.CPP and check out the syntax of the variables
closely. Look for other new features that have not been shown in any one of the
previous program examples.

// PROG0502.CPP
// This program introduces integer, character and real
number
// variables. This program also demonstrates the use
of an
// assignment operator.

#include <iostream.h>
#include <conio.h>

void main()
{
int Var1; // integer variable
char Var2; // character variable
float Var3; // real number (floating point)
variable

Var1 = 5000; // integer assignment


Var2 = 'A'; // character assignment
Var3 = 3.14159; // real number assignment

clrscr();
cout << Var1 << endl;
cout << Var2 << endl;
cout << Var3 << endl;
getch();
}

PROG0502.CPP OUTPUT

5000
A
3.14159

The program code is divided up into three segments: The variable definition
segment, the assignment segment, and the output segment. The variable
definition segment shows the definition of three variables. The names of these

Chapter V Variables and Constants 5.4


variables can be virtually anything. In this case, names like Var1, Var2 and
Var3 seem appropriate. The special C++ keywords int, char and float are called
“reserved words” and reserved words have a special meaning in a program.

C++ has a few restrictions on the choice of your identifiers. You are not allowed
to create any variables with identifiers that are already reserved words in C++. It
is not difficult to recognize reserved words in C++. All the modern C++
compilers use special highlighting or different color for any C++ keywords in a
program that are reserved words.

Looking at program PROG0502.CPP you will notice that some words are in
lower case and other words are capitalized. This is not a casual choice. You need
to watch out with capitalization. A few changes turns the last program into the
totally different program, PROG0503.CPP.

// PROG0503.CPP
// This program demonstrates that C++ is case
sensitive.

#include <iostream.h>
#include <conio.h>

void main()
{
int Var1; // integer variable
char Var2; // character variable
float Var3; // real number (floating point)
variable
Var1 = 5000; // integer assignment
Var2 = 'A'; // character assignment
Var3 = 3.14159; // real number assignment

clrscr();
cout << var1 << endl;
cout << var2 << endl;
cout << var3 << endl;
getch();
}

Do not look for any program output with this example. None will be available
because this program does not compile. Any attempt at compiling this program
will generate error messages similar to the following ones:

Chapter V Variables and Constants 5.5


Message
Compiling PROG0503.CPP
Error PROG0503.CPP 18: Undefined symbol ’var1’
Error PROG0503.CPP 18: Undefined symbol ’var2’
Error PROG0503.CPP 18: Undefined symbol ’var3’
Warning PROG0503.CPP 22: ’Var3 is assigned a value that is never used
Warning PROG0503.CPP 22: ’Var2 is assigned a value that is never used
Warning PROG0503.CPP 22: ’Var1 is assigned a value that is never used

There is no reason to get excited about all these warnings. You will get plenty of
warnings when the compiler is just having a bad day. The real concern here is to
look at the error messages. Apparently, three variables are not defined. The
compiler cannot find the definitions for var1, var2 and var3. This may seem odd
to you, but remember that C++ is case sensitive. Variables Var1 and var1 are not
the same identifiers to the eyes of the C++ compiler.
Important Warning About Case Sensitivity

C++ is case sensitive.


This means that GrossPay and grosspay are two completely
different identifiers to C++.

Students frequently get confused about “case sensitivity.” You may notice that
reserved words and other C++ keywords are in lower-case. This observation can
cause you to conclude that C++ requires using lower-case. This is not true.
Yes, the greater majority of C++ keywords are in lower case but the program
examples you have seen include identifiers with upper case letters. Just make
sure that you are aware of when to use lower case and when to use upper case.

How can you tell this difference? The examples in this book follow a certain
style format. I like to make it easy to identify C++ keywords and programmer
identifiers. Almost all C++ keywords are in lower-case (you will learn about the
exceptions later), so I make my identifiers start with an upper-case letter. If an
identifier is more than one word, I start the next word with an upper-case letter as
well. This makes the identifier more readable.

The Assignment Operator

The two previous program examples included the program statements below. At
first glance it may appear like an equation because the equality = sign is used.

Chapter V Variables and Constants 5.6


Var1 = 5000; // integer assignment
Var2 = 'A'; // character assignment
Var3 = 3.14159; // real number assignment

The program statement Var1 = 5000; certainly looks like an equation. It is


tempting to say “Var1 equals 5000.” Saying equals will not really confuse
people who understand the C++ programming language, but it is more correct to
say something like: Var1 gets 5000
Var1 becomes 5000
5000 is assigned to Var1

Chapter VI will focus on the operations that can be performed with integers,
characters, floats and string variables. Right now only the addition + operation
will be used to help explain the assignment operator. In program
PROG0504.CPP the program statement N1 = 100 + 200; evaluates the
arithmetic expression 100 + 200 and assigns the sum 300 to variable N1.

// PROG0504.CPP
// This program demonstrates that the assignment
operator can be
// used for evaluating mathematical expressions. The
program also
// shows program output that mixes constants with
variables.

#include <iostream.h>
#include <conio.h>

void main()
{
clrscr();
int N1 = 10, N2 = 20, N3 = 30;
cout << N1 << " " << N2 << " " << N3 << endl;
N1 = 100 + 200;
N2 = 500 + 300;
N3 = -100 + -200;
cout << endl;
cout << N1 << " " << N2 << " " << N3 << endl;
N1 = N2 + 400;
N2 = N1 + 600;
N3 = N1 + N2;

Chapter V Variables and Constants 5.7


cout << endl;
cout << N1 << " " << N2 << " " << N3 << endl;
getch();
}

PROG0504.CPP OUTPUT

10 20 30

300 800 -300

1200 1800 3000

You will note in the previous program example, PROG0504.CPP, that the
expression on the right hand side of the assignment operator can be constants
only, like N1 = 100 + 200. The right hand expression can also be mixed
variables and constants, like the program statement N2 = N1 + 600. Finally,
it is possible that the expression has only variables like N3 = N1 + N2;.

Assignment Operator Syntax

Variable = Expression;
Rate = 8.765;
Sum = X + 13;
Total = N1 + N2 + N3;

Wrong Assignment Operator Syntax

Do not switch the left and right side of an assignment operator.


The following examples will not work.
8.765 = Rate;

Chapter V Variables and Constants 5.8


12 + 13 = Sum;
N1 + N2 + N3 = Total;

The mathematical equal sign = that is used for the C++ assignment operator
causes people sometimes to think that it means equality. Perhaps you think that a
statement like X=Y+4 is an equation. It certainly looks like an equation and you
may well assume that in C++ the equal = sign means equality.

It is important to realize that assignment is not the same as equality. If the


assignment operator is in fact an equal sign, and program assignment statements
are equations, then the statements X=Y+4 and Y+4=X would be identical. This
is definitely wrong and violates the proper syntax rules explained earlier.

The next program example, PROG0505.CPP will be used to demonstrate that


equality cannot be true with an assignment statement. Study the syntax carefully.
Some statements may look weird, but they only look weird if you think equality.

// PROG0505.CPP
// This program demonstrates that the assignment
operator is not
// an equal sign. An assignment statement is not an
equation.

#include <iostream.h>
#include <conio.h>

void main()
{
clrscr();
int Number = 1000;
cout << Number << endl;
cout << endl;
Number = Number + 100;
cout << Number << endl;
Number = Number + Number;
cout << endl;
cout << Number << endl;
getch();
}

Chapter V Variables and Constants 5.9


PROG0505.CPP OUTPUT

1000

1100

2200

Do you think Number = Number + 100 is a strange program statement? It


is not, and it demonstrates that equality is not at work here. So what is happening
anyway? The variable Number has some memory reserved somewhere in RAM.
The program statement tells the computer to find the value of Number, add 100
to the value, and then put the sum back in the memory location. The same logic
applies to the statement Number = Number + Number. Perhaps the
following analogy will help to clarify what is happening. Imagine a school
without a computerized registration system. The counselors have large, laminated
boards with squares indicating subjects and periods. The counselors must keep a
close eye on the board to prevent overloading any classes. Now imagine that
three students want to take Algebra II, Mr. Jones, 2nd Period. This situation can
be described as:
AlgIIJonesP2 = AlgIIJonesP2 + 3

A counselor helper goes to the board, and signals that the class is not filled. The
helper states that 23 students are currently enrolled for the requested class. The
new enrollment of 3 is added to 23. The number 23 is erased from the board and
replaced with the number 26. This process is pretty much what happens with an
assignment statement. The board is a cell somewhere in computer memory and
the CPU is the counselor.
5.3 Mixing Data Types

C++ uses different data types. So far you have been introduced to int, char and
float. In every program example you saw that program variables must be defined
before they can be used. This definition requires using the reserved words int,
char or float before the variable identifier name. I mentioned that memory
efficiency is improved by defining the type of a variable. Different variables
require different amounts of memory space. The exact memory requirement will
be explained in the next chapter.

Chapter V Variables and Constants 5.10


The program examples you have seen so far have been logical. Logical in the
sense that only integer values were assigned to int variables, characters to char
variables, and real numbers to float variables.

You might, without realizing it, assign values to the wrong variables. Will the
compiler catch such a mistake? If the compiler does not catch it, what is going to
happen? These are good questions and program PROG0506.CPP is designed
precisely to answer these questions.

This next program example does some pretty bizarre stuff. You will see a letter
character assigned to an int variable, a number assigned to a char variable, and a
variety of other peculiar assignments that all seem to violate proper assignment
practice. Make sure to follow the assignment advice on the next page.

Assignment Advice

When in doubt assign like data types, like:

int X, Y;
char Letter1, Letter2;
X = 10;
Y = X;
X = X + Y;
Letter1 = 'A';
Letter2 = Letter1;

Only mix data type assignments when this serves a specific


purpose, and you know the result of the assignment.

// PROG0506.CPP
// This program demonstrates that it is possible to mix
// data types in assignment statements.

#include <iostream.h>
#include <conio.h>

void main()
{
int IntVar;
char CharVar;
float FloatVar;
IntVar = 'A';

Chapter V Variables and Constants 5.11


CharVar = 65;
FloatVar = 25;
clrscr();
cout << "IntVar = 'A' " << IntVar << endl;
cout << "CharVar = 65 " << CharVar << endl;
cout << "FloatVar = 25 " << FloatVar << endl;
IntVar = 3.14159;
CharVar = 'A' + 5;
FloatVar = 'B';
cout << endl;
cout << "IntVar = 3.14159 " << IntVar << endl;
cout << "CharVar = 'A' + 5 " << CharVar << endl;
cout << "FloatVar = 'B' " << FloatVar << endl;
getch();
}

PROG0506.CPP OUTPUT

IntVar = 'A' 65
CharVar = 65 A
FloatVar = 25 25

IntVar = 3.14159 3
CharVar = 'A' + 5 F
FloatVar = 'B' 66

The advice on the previous page does not need to be repeated for you. You
should not add the number 5 to the character A and then assign this to a character
value. But honestly now, had you expected that this program would even
compile? The program output seems a fair indication that the compiler is not
unhappy with the peculiar assignments. So what is the story here?

The story revolves around C++ trying hard to make the programmer happy and
making some decent guesses about what is going on. You can couple this with
the fact that information is stored as numbers and the output is not quite so odd.

For instance, assigning letter A to an integer results in the value 65. Logical?
Well, yes, consider that the ASCII value (you know the special code) for A = 65.

Assigning the number 65 to a character variable gives the exact opposite result.
This time a number is assigned and taken as the ASCII value of the character
variable. The result is that A is displayed.

There is not much problem assigning an integer to a float. After all, integers are
subsets of real numbers. However, assigning a real number to an integer is a

Chapter V Variables and Constants 5.12


different story. The program example tries to assign 3.14159 to an integer, and
integer variables are not equipped to store fractional parts. Does C++ get excited?
Hardly, just chop of the fraction and assign the truncated real number.

Perhaps the strangest assignment is ’A’ + 5, which apparently outputs F. Once


again, I hope you will see the logic here. The character code for capital A is 65.
The computer can handle 65 + 5 and gets 70. The character associated with code
70 is F. Pretty smart computer, don’t you think?

But please, until you have a better understanding, be careful with mixing data
type assignments. You can get some pretty bizarre results. The programming
language C++ was designed to be an industrial strength language. Many, many,
many capabilities are available for the expert programmer who wants maximum
flexibility with program development. This nifty flexibility can be a dangerous
tool in the hands of the student new to computer science. Do not be surprised
when the computer objects to your programs and rewards you with a “lockup” or
a “courtesy reboot.” I call a “courtesy reboot” when C++ considers your program
attempt so bizarre that the computer automatically reboots the computer to let you
start again. In other situations you will need to do the rebooting.

Save Advice

Always save your programs before you try to compile/execute.

Sooner or later you will find that the computer "locks up" and
requires rebooting.

Rebooting a computer means the loss of data that is stored


temporarily in computer memory, RAM. The programs you
write are data that is stored temporarily in memory. Unless
you acquire a habit to store your program permanently on
a hard drive, diskette or network, you run the risk of losing
many hours or computer work.

5.4 Initialized Variables

In some of the previous programs you have seen program statements like:

X = X + 4;

Chapter V Variables and Constants 5.13


This type of statement assumes an initial value for X. The CPU finds the value
for X, adds 4 to this value and returns the sum to the memory location of X.
Clean and simple, right? True, but what if there is no initial value for X? What
will the CPU do? Well, the CPU will do the exact same process. This time there
is a little problem. The memory location for X always has a value because there
are a bunch of bits sitting around turned on or off. This means that the computer
will evaluate your expression with some unknown, random value in memory.

The problem of forgetting to initialize variables can be handled by initializing


variables at the time that they are defined. Many programmers do this
automatically. The syntax for initializing a variable is a combination of a variable
definition and an assignment statement. Program PROG0507.CPP demonstrates
the required syntax for initialized variables.

// PROG0507.CPP
// This program demonstrates how to define and
initialize a
// variable in the same statement.

#include <iostream.h>
#include <conio.h>

void main()
{
int IntVar1 = 25;
int IntVar2 = 50;
char CharVar1 = '#';
char CharVar2 = '$';
clrscr();
cout << IntVar1 << " " << IntVar2 << endl;
cout << CharVar1 << " " << CharVar2 << endl;
IntVar1 = IntVar1 + 1000;
IntVar2 = IntVar2 + 2000;
CharVar1 = '1';
CharVar2 = '2';
cout << endl << endl;
cout << IntVar1 << " " << IntVar2 << endl;
cout << CharVar1 << " " << CharVar2 << endl;
getch();
}

Chapter V Variables and Constants 5.14


PROG0507.CPP OUTPUT

25 50
# $

1025 2050
1 2

This program shows something besides initialized variables. It shows that a


number can be a character. This time I do not mean a number like 65, which is
the code value for the character A. I mean that there are numerical characters,
like ’1’ and ’2’. You can distinguish number values from numerical characters by
the single quotes. All character constants are assigned with single quotes.
Numbers do not use quotes at all.

When should you define, and initialize, your variables? Right now that is a tough
question to answer. You will need to get many more tools under your belt. In
general this first book will strictly focus on teaching you the syntax of the
different C++ features. The “should” or “should not” will be presented at places,
but sparingly. It is a little like learning to play a new card game. All card games
have special strategies for playing the game better. These strategies include
certain actions that should and should not be done with certain situations. The
truth is that the new game player is happy just to know the rules and get started.
The fine nuances come later after some experience. It is the same with computer
science. At this stage accept that it is a good habit to initialize variables as they
are defined. Your teacher will offer further advice with the “should” issues.

5.5 Program Sequence

At this stage you pretty much understand that the magic compiler takes the C++
program that you have written and translates your C++ source code into binary
machine code. With machine code the computer can happily digest the binary
code and performs a variety of required tasks. But how does the computer know
what to do, and when to do it? The answer is sequence. The program is executed
in the precise sequence of the program statements created by you.

Chapter V Variables and Constants 5.15


Now there will be many students who are surprised that I bother to mention this.
Perhaps you have the intuitive logic to realize where to use program statements.
On the other hand, the program on the next page presents a problem that I have
witnessed duplicated many times by students new to programming.

// PROG0508.CPP
// This program demonstrates that program execution is
controlled
// by program statement sequence.

#include <iostream.h>
#include <conio.h>

void main()
{
int IntNumber;
float FloatNumber;
clrscr();
cout << "IntNumber = " << IntNumber << endl;
IntNumber = 2500;
cout << "IntNumber = " << IntNumber << endl;
IntNumber = 5000;
cout << "FloatNumber = " << FloatNumber << endl;
FloatNumber = 33.333333;
cout << "FloatNumber = " << FloatNumber << endl;
FloatNumber = 66.666666;
getch();
}

PROG0508.CPP ACTUAL OUTPUT

IntNumber = 2418
IntNumber = 2500
FloatNumber = 1.1255e-11
FloatNumber = 33.333332

There certainly is something wrong with the output of PROG0508.CPP.


Perhaps you had expected a program output more along the following lines.

PROG0508.CPP EXPECTED OUTPUT

IntNumber = 2500
IntNumber = 5000

Chapter V Variables and Constants 5.16


FloatNumber = 33.333333
FloatNumber = 66.666666

The expected output seems very natural, doesn’t it? Each number displays the
value assigned in the program. It is true that you see the assigned values, but the
more important concern is program sequence. When were those values assigned
and when was the program supposed to produce output? The CPU is going to
execute the program in the precise sequence that the program was written. The
first program statement will be executed first, the second statement next, etc..
The problem is best explained by focusing on the following first five program
statements extracted from the program:

int IntNumber;
float FloatNumberl
clrscr();
cout << "IntNumber = " << IntNumber << endl;
IntNumber = 2500;

The first two program statements define an integer variable and a float variable.
C++ will happily oblige and set aside space in memory for one integer and for one
real number.

There is also no problem with the clrscr(); command. That statement comes
first and clears the screen to avoid any previous clutter.

With the very next statement the value of IntNumber is supposed to be


displayed. The CPU once again has no problem with that instruction. There
exists a memory location for IntNumber and the CPU takes a peek in the
memory to determine the value, and then displays the value.

Now there will be a value in the memory location for IntNumber. Every BIT in
memory has the value of 0 or 1 and combinations of 16 bits are used to store an
integer. My computer happened to find 2418, which is surprisingly close to 2500,
but the value could be anything. You will probably get a different value on your
computer.

At this point many students object. You may be one of these students. You
object on the ground that the program clearly shows the value 2500 being
assigned to IntNumber. You are right, but the problem is that the assignment
occurs after the output statement. You see, incorrect program sequence is the
problem here.

Chapter V Variables and Constants 5.17


You still are not convinced? I have a deal for you. I am going to give you
$100.00 if you can correctly solve an addition problem I am going to give to you.
There is one slight catch with the problem. First you need to give me the correct
answer, and then I will give you the problem. So far I have not passed out too
many $100.00 bills.

The previous example is somewhat subtle. It is subtle in the sense that the
program did compile and it did run. It just did not run as you expected. There are
times when failure to obey proper sequence will not even let you get started, like
is demonstrated with program PROG0509.CPP.

// PROG0509.CPP
// This is another example that demonstrates why you
must use
// correct program sequence. This program does not
compile.

#include <iostream.h>
#include <conio.h>

void main()
{
clrscr();
cout << "IntNumber = " << IntNumber << endl;
IntNumber = 2500;
cout << "IntNumber = " << IntNumber << endl;
IntNumber = 5000;
cout << "FloatNumber = " << FloatNumber << endl;
FloatNumber = 33.333333;
cout << "FloatNumber = " << FloatNumber << endl;
FloatNumber = 66.666666;
int IntNumber;
float FloatNumber;
getch();
}

PROG0509.CPP OUTPUT

There is no program output.


The program will not compile.
Some messages indicating that IntNumber and FloatNumber are
undefined will be your only output appearance.

Chapter V Variables and Constants 5.18


This program example demonstrates some very significant C++ programming
concepts. You need to be careful that the order of your program statements
follows a logical sequence that will insure a correct program execution. However,
there is another issue. C++ is going to object tremendously if you use any
identifier that is not defined.

Now from the compiler’s point of view it matters little if you totally leave out a
variable definition or if you place the definition in the wrong place. In the
program above, the variable definitions were placed at the very end. The
compiler simply is not satisfied with that. At the precise point that the C++
compiler encounters the variable IntNumber for the first time, it needs to know
what is happening.

When the compiler encounters an identifier, it must decide if the identifier is legal
in the present program, and if compiling is possible with this identifier. There are
only three possibilities: IntNumber is a C++ reserved word, which means that
it is part of the C++ language. IntNumber is a library function that is available
because your program has included the necessary library, like #include
<conio.h> IntNumber is a variable identifier created by the programmer, which
means there has to be a variable definition before the variable is used.

Identifier Rule

All identifiers must be “known” to C++ before they can be used.


C++ checks identifiers three ways:
1. Is the identifier a reserved word?
2. Is the identifier a library function?
3. Is the identifier defined in the program?

5.6 String Variables

Chapter V Variables and Constants 5.19


This chapter has introduced int for integer variables, float for real number
variables and char for character variables. With these three data types, you can
do a fair amount of programming, but an important data type is missing, the
string. In computer science a string is a group of characters. As a matter of fact,
you are reading a bunch of strings that are used to explain this concept.

C++ is finalizing a standard for the language. This standard includes some very
good features that all C++ compilers should have available. The new string type,
as defined by the C++ standard, is not available on most C++ compilers. This is
logical because most C++ compilers were developed before the C++ standard was
finalized. The Advanced Placement Computer Science (APCS) Committee is the
committee responsible for creating the APCS examination. They have created a
variety of C++ tools that are based on the “soon to be released” C++ standard.
These tools allow us to use older C++ compilers with newer features. One such
feature is the apstring data type. The new standard will not have the ap included,
but the APCS committee decided to include ap will all the provided tools. This
distinction lets you know that it is not part of the current C++ compiler, but
developed by the APCS committee. However, you will be able to use these new
features in a very convenient manner. Throughout the course the AP
enhancements will be explained as it is appropriate. Right now it is appropriate to
talk about the apstring type. Using apstring is not very different from using int,
float and char. There is however, an important file that must be included.

Apstring Inclusion

You must use the statement


#include "APSTRING.H"
to have access to the special apstring data type.

The format "APSTRING.H" is used at Berkner High School


by Mr. Schram. Your teacher may use a different include
approach, such as "apstring.cpp."

The quotes will appear strange to use. All program examples have used program
statements for library functions that use angle brackets, like:

#include <iostream.h>
#include <conio.h>

Now you are expected to use library functions with slightly different syntax, like:

Chapter V Variables and Constants 5.20


#include "apstring.h"
or
#include "APSTRING.H"

The double quotes indicate to the C++ compiler that this is a special library file.
Normally C++ goes to a designated location to find the included library functions.
There is a special setting in the IDE that allows you to designate where the C++
compiler can find the included library files.

A programmer also has the option to include their own library files. These files
will normally be located in the same place as your programs. This may be on a
floppy diskette, a special location on the hard drive, or a designated location on
the network. When you first bootup C++, you need to change directories to the
location where your files are placed. In the “logged-on” subdirectory, is where
the compiler will look for the include file with the double quotes.

Personally, I like to make include file names in capital letters. You may be
concerned here, since you remember a “Case Sensitivity” lecture. You are so
right, but apstring.h is not a C++ identifier, it is file name for some type of
external storage area. File names are not case sensitive, so there is no problem.

// PROG0510.CPP
// This program introduces the string variable with
apstring.

#include <iostream.h>
#include <conio.h>
#include "APSTRING.H"

void main()
{
apstring Name1; // 1st string variable;
apstring Name2; // 2nd string variable;

Name1 = "Suzie Snodgrass";


Name2 = "Seymour Schmittlap";

clrscr();
cout << "Name1 = " << Name1 << endl;
cout << "Name2 = " << Name2 << endl;
getch();
}

Chapter V Variables and Constants 5.21


PROG0510.CPP OUTPUT

Name1 = Suzie Snodgrass


Name2 = Seymour Schmittlap

Once you remember to include apstring with the unusual double quotes
approach, you will find this data type pretty similar to other data types. Defining
a variable string type is done like any other variable data type. Furthermore, you
will observe that the assignment = operator behaves in the exact same manner as
any data type, which was previously introduced.

The apstring program shows assignment with a string constant. You have seen
in previous programs, with other data types, that constants can be assigned, as
well as variables. In the next program example you will see that a string variable
can also be assigned to a string variable exactly like the previous data types.

// PROG0511.CPP
// This program demonstrates how to initialize a string
variable.
// The program also shows incorrect value swapping.

#include <iostream.h>
#include <conio.h>
#include "APSTRING.H"

void main()
{
apstring Name1 = "Kathy"; // 1st initialized string
variable;
apstring Name2 = "Tommy"; // 2nd initialized string
variable;

clrscr();
cout << "Name1 = " << Name1 << endl;
cout << "Name2 = " << Name2 << endl;

Name1 = Name2;
Name2 = Name1;

cout << endl;


cout << "Name1 = " << Name1 << endl;
cout << "Name2 = " << Name2 << endl;
getch();

Chapter V Variables and Constants 5.22


}

PROG0511.CPP OUTPUT

Name1 = Kathy
Name2 = Tommy

Name1 = Tommy
Name2 = Tommy

This program does more than demonstrate how to assign string variables. You
will observe that Name1 = Name2; causes no problems. Assignment follows the
pattern established with previous programs. You are a happy person and life is
good. Life however would be better if the output would be a little more logically
agreeable.

A quick glance at the program code shows that Name1 becomes Name2 and
Name2 becomes Name1. Another quick glance shows that the program output
does not swap the values. It is very important that you realize the logic that is
happening here. Let us “step” through the program and use diagrams to show the
values in the memory locations for Name1 and Name2.
This is the result, in memory, after the two program statements:

apstring Name1 = "Kathy";


apstring Name2 = "Tommy";

Name1 Name2

Kathy Tommy

The next assignment statement is crucial. It helps to explain what is happening.


Name1 gets the value from Name2. The result is that now both string variables
contain the exact same value.

Name1 = Name2;

Name1 Name2

Tommy Tommy

Chapter V Variables and Constants 5.23


The final program statement does not alter anything. It appears that values are
swapped, but swapping is not possible, since the value of “Kathy” was lost.

Name2 = Name1;

Name1 Name2

Tommy Tommy

Curiosity is rapidly growing in your brain. I can sense it, and I have written this
paragraph long before you are reading it. Still, I feel and believe that you are
desperate to know how a person can then swap values. The previous program did
prove that a variable string value can be assigned to another string variable, but
you also witnessed the demise of “Kathy.” You will be pleased to know that
there is another program that will demonstrate variable string assignment and this
time we will not lose any variable string values in the swapping business.

// PROG0512.CPP
// This program demonstrates the correct swapping of
two variable
// values by using an extra variable.

#include <iostream.h>
#include <conio.h>
#include "APSTRING.H"

void main()
{
apstring Animal1;
apstring Animal2;
apstring Temp;

Animal1 = "Tiger";
Animal2 = "Giraffe";

clrscr();
cout << "Animal1 = " << Animal1 << endl;
cout << "Animal2 = " << Animal2 << endl;

Temp = Animal1;
Animal1 = Animal2;

Chapter V Variables and Constants 5.24


Animal2 = Temp;

cout << endl;


cout << "Animal1 = " << Animal1 << endl;
cout << "Animal2 = " << Animal2 << endl;

getch();
}

PROG0512.CPP OUTPUT

Animal1 = Tiger
Animal2 = Giraffe

Animal1 = Giraffe
Animal2 = Tiger

The secret is a third string variable, called Temp. Temp’s only mission in life is
to assist Animal1 and Animal2 with swapping values. I will demonstrate the
same diagram sequence as before, but this time a third string variable is included.

Swapping Correctly with a Temporary Placeholder

Animal1 = "Tiger";
Animal2 = "Giraffe";

Animal1 Animal2 Temp

Tiger Giraffe unknown

We know from previous experience that the value in Animal1 is likely to be


endangered. The next assignment statement preserves the Tiger value.

Chapter V Variables and Constants 5.25


Temp = Animal1;

Animal1 Animal2 Temp

Tiger Giraffe Tiger

With Tiger safely tugged away in Temp, we can copy the Giraffe value to
Animal1 without losing anything.

Animal1 = Animal2;

Animal1 Animal2 Temp

Giraffe Giraffe Tiger

We now observe the same situation as before. Both Animal1 and Animal2 store
the same string value. However, this time Tiger is lurking in the Temp location
ready to jump into action with the next assignment statement.

Animal2 = Temp;

Animal1 Animal2 Temp

Giraffe Tiger Tiger


Frequently, programming languages allow you to accomplish similar goals in
multiple ways. As a rule, it can be pretty confusing to be bombarded by all the
possible solutions to the same problem. That is somewhat like arriving in a new
city and people give you five sets of directions to get to your new job location. At
first, you really only want to get there one simple way.

You do need to realize that accomplishing some task in a different way can set the
stage for some future different concept. Such is the case with the next program
example. You will see that a new apstring variable can be initialized two
different ways. You have already seen one method using the assignment
statement. It is also possible to place the initial value in parenthesis following the
apstring identifier. Which method is better? At this stage that matters little. You
will encounter both methods in program examples.

The second, parenthesis method, will become especially important in future


topics. One technique in technical manuals in general, and Exposure C++
specifically, is to plant some early seeds that can be utilized later.

Chapter V Variables and Constants 5.26


// PROG0513.CPP
// This program demonstrates that string variables can be
// defined and initialized two different ways.

#include <iostream.h>
#include <conio.h>
#include "APSTRING.H"

void main()
{
apstring String1 = "First String";
apstring String2("Second String");

clrscr();
cout << "String 1 = " << String1 << endl;
cout << "String 2 = " << String2 << endl;
getch();
}

PROG0513.CPP OUTPUT

String 1 = First String


String 2 = Second String

5.7 Program Constants

The title of this chapter is Variables and Constants. You will find the Variables
part is heavy and the Constants part is light. But, we do mention the heavy part
first. I decided not to use the Pork ‘N Beans approach. Perhaps you are
somewhat confused right now. Maybe you feel that constants have been covered
already. We did look at int constants like 500, and we looked at float constants
like 3.14159, and we looked at char constants like ’A’, and finally we did look at
apstring constants like ”Good Morning.” So if we did show how to assign
constants to a variable, why bother with a special Constants section.

What we have not covered yet are constants that use an identifier, called symbolic
constants. In this case we want to use an identifier and it looks just like a
variable, but it is a constant. One really terrific clue that an identifier is a constant

Chapter V Variables and Constants 5.27


is the appearance of the C++ reserved word const in front of the identifier, like in
program PROG0514.CPP.

// PROG0514.CPP
// This program demonstrates how to use the reserved
word const.

#include <iostream.h>
#include <conio.h>
#include "APSTRING.H"

const int MAX = 5000;


const float PI = 3.14159;
const char START = 'A';
const apstring GREETING = "Good Morning";

void main()
{
clrscr();
cout << "MAX: " << MAX << endl;
cout << "PI: " << PI << endl;
cout << "START: " << START << endl;
cout << "GREETING: " << GREETING << endl;
getch();
}

PROG0514.CPP OUTPUT

MAX: 5000
PI: 3.14159
START: A
Greeting: Good Morning

You should have noted two differences between the variable definitions of the
previous programs and the constants of program PROG0514.CPP.

First, the word const is used in front of what normally would be a variable
definition.

Second, the const statements are located near the top of the program and not
inside the braces { } of the main function.

The word const is logical. You are stating that the identifier that follows will get
one value and it had better be happy about that one value. There are not going to

Chapter V Variables and Constants 5.28


be any changes. In a small program there will seem little value in using any
constants. In a large program there are some benefits. Certain values change very
rarely, but when they do, changing the const value at the top of the program will
make a change throughout the program.

The second difference - the constant statements appearing above main - makes
the constants global. This means that the constant identifiers can be used
anywhere in the program. At this stage this simply means in the main part of the
program. However, doesn’t main imply something that is not main. We have not
seen that yet, but you will soon.

Right now you have to realize and accept something. The nature of computer
science is that you are frequently introduced to concepts and tools that are
difficult to justify at their introduction. Do have patience, and faith, that clarity
will be around the corner. If clarity is not around the corner, hike a few more
blocks and you will see the light soon enough. I have seen many a beginning
skier grumbling about a tiring exercise of side stepping up a hill. I see such skiers
looking at the many comfortable ski lifts heading up the mountain. Beginning
skiers are a simple lot --- to them the lift takes you up and gravity brings you
down. Later in the trip these jolly beginners lose a pole or they need to assist a
buddy who falls down. Oh no, there is not a short-distance lift, and you need to
move up the steep mountain. Well what do you know, those dumb ol’ side step
exercises are coming in handy after all.

Syntax for Using const

const data-type identifier = constant value


const int MAX = 5000;
It is a common convention, not a requirement, to use all capital
letter for a const identifier.

Mr. Schram You Are Wrong!!!

I can just hear some of you saying this. Every year I have bright, motivated
students who have already taught themselves a good chunk of C or C++.
Carefully these experts read my books, ever on the alert for a mistake. This const
business is wrong.

Mr. Schram (that is me) claims that the const syntax is something like:

const int MAX = 500;

And you - C++ expert that you are - know for a fact that it is possible to say:

Chapter V Variables and Constants 5.29


const MAX = 500;

Well felicitations and salutations to you. You are so right. So why did I show
you it differently? The syntax I showed you works for all types. The abbreviated
syntax without a data type does not work in all cases. Consider
PROG0515.CPP, which is identical to the previous program, except the data
types are not provided in the const statements. The const string is intentionally
commented out. Run the program both ways and see what happens.

// PROG0515.CPP
// This program demonstrates that it is important to provide the
// data type in a const statement.

#include <iostream.h>
#include <conio.h>
#include "APSTRING.H"

const MAX = 5000;


const PI = 3.14159;
const START = 'A';
//const GREETING = "Good Morning";

void main()
{
clrscr();
cout << "MAX: " << MAX << endl;
cout << "PI: " << PI << endl;
cout << "START: " << START << endl;
// cout << "GREETING: " << GREETING << endl;
getch();
}

PROG0515.CPP OUTPUT

MAX: 5000
PI: 3
START: 65

Now you need to pay attention. Perhaps you do not see the problem. The integer
MAX is quite happy with the value 5000. The real number PI loses its fractional
part and the character START displays an integer. And hold on because it gets
worse. Try to remove the comments from the string constant. You will find that

Chapter V Variables and Constants 5.30


the program does not even compile then. There may have been a temptation to
think that several approaches were available. In the case of int it appears to
matter little, but other data types have problems. There are many situations where
it is possible to use multiple approaches to achieve the same result. You just saw
one example where it is easy to get the wrong impression.

This brings up an important point. Do not expect to be shown every possible way
that something can be accomplished in C++. This C++ language is one large,
complicated language, and the choices are incredible. By the time you finish this
course, and maybe the next one, you will have a very, very healthy knowledge
base of C++. And nobody is stopping you from learning every little peculiar C++
trick. For now do not expect me to show you everything. It wastes time, paper
and little useful knowledge is gained.

Is A Constant Really a Constant?

Some of you may wonder what happens when you mess with an identifier that has
been declared as a const? It takes little space to explain, but it makes more sense
if you try. Type in the program below, or load PROG0516.CPP from disk.

This program declares four different constants. After the constants are declared
you will notice that an attempt is made to assign new values to these constant
identifiers. The word attempt is made because you will find that the compiler is
not real happy with you.

You will get a group of error messages that make it clear that the compiler is not
letting you try this little experiment. Most compilers will respond with:

Error PROG0516.CPP 15: Cannot modify a const object

// PROG0516.CPP
// This program demonstrates that it is not possible to
// modify a constant object.

#include <iostream.h>
#include <conio.h>
#include "APSTRING.H"

const int MAX = 5000;


const float PI = 3.14159;
const char START = 'A';
const apstring GREETING = "Good Morning";

Chapter V Variables and Constants 5.31


void main()
{
clrscr();
MAX = 10000;
PI = 123.456
START = 'Q';
GREETING = "Good Afternoon";
cout << "MAX: " << MAX << endl;
cout << "PI: " << PI << endl;
cout << "START: " << START << endl;
cout << "GREETING: " << GREETING << endl;
getch();
}

Literal Constants and Symbolic Constants

Examples of literal constants are 2500, 12.75 and Joe Smith.

Number = 2500;
PayRate = 12.75;
Name = "Joe Smith";

Examples of symbolic constants are Nbr, PR, and Word.

const int Nbr = 10000;


const float PR = 9.25;
const apstring Word = "QWERTY";

Symbolic constants cannot be modified.

There remains one more situation that should be investigated. You have seen
values assigned to const identifiers, and that worked fine. You have also been
shown that an attempt to alter any const identifier prevents successful compiling.
Now how about assigning a const value to a variable identifier? No problem at
all. C++ is more than happy to let you use constants in practically every situation.
The only important restriction is that you do not try to alter the constant value.
There is no point in calling an identifier a constant if a constant can be changed.

Chapter V Variables and Constants 5.32


// PROG0517.CPP
// This program demonstrates that a constant object can
be
// assigned to a variable.

#include <iostream.h>
#include <conio.h>
#include "APSTRING.H"

const int MAX = 5000;


const float PI = 3.14159;
const char START = 'A';
const apstring GREETING = "Good Morning";

void main()
{
clrscr();
int IntVar;
float FloatVar;
char CharVar;
apstring StringVar;
IntVar = MAX;
FloatVar = PI;
CharVar = START;
StringVar = GREETING;
cout << "IntVar: " << IntVar << endl;
cout << "FloatVar: " << FloatVar << endl;
cout << "CharVar: " << CharVar << endl;
cout << "StringVar: " << StringVar << endl;
getch();
}

PROG0517.CPP OUTPUT

IntVar: 5000
FloatVar: 3.14159
CharVar: A
StringVar: Good Morning

Chapter V Variables and Constants 5.33


Chapter V Variables and Constants 5.34

You might also like