09/24/2006 09/24/2006
Introduction to C++
Vocabulary
Whitespace-characters whose printed representation is blank: space, tab, and newline.
www.cs.utexas.edu/users/novak/cs307vocab.html
Defining and Assigning Variables
Variable Definition Syntax
datatype Variable Identifier // optional but desired comment
int Number;
char Choice;
// 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
Important Warning About Case Sensitivity
C++ is case sensitive.
This means that GrossPay and grosspay are two completely different identifiers to C++.
The Assignment Operator
Var1 = 5000; // integer assignment
Var2 = 'A'; // character assignment
Var3 = 3.14159; // real number assignment
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;
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;
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();
}
PROG0505.CPP OUTPUT
1000
1100
2200
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 Different variables require different amounts of memory space.
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';
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
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.
Initialized Variables
In some of the previous programs you have seen program statements like:
X = X + 4;
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();
}
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.
Program Sequence
At this stage you pretty much understand that the 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.
// 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
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.
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.
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?