SlideShare a Scribd company logo
1 of 14
Download to read offline
© 1998, 2010 by Lindsey Anderson. All Rights Reserved.
Introduction to Programming in C++
By Lindsey Anderson
I wrote 4 chapters of an unpublished book on Programming in C++. The following Chapter 1 is
presented here to demonstrate my ability to describe complex material in a simple, straightforward
manner.
1
Introduction & Overview
The best way to learn a foreign language, some sages say, is to totally immerse yourself in the
language. We are going to use the total immersion technique with C++. Take a look at the following
program:
/* This program uses Einstein’s famous equation, E=mc2
, from his
Theory of Relativity to convert a given mass (in kilograms) into
energy */
#include <iostream.h> //library containing cin, cout,
//<<, & >>
#include <math.h> //library containing power function pow()
const float LIGHT_SPEED=2.9977925e8;
/* declaring constant for speed of light in meters/sec */
float main()
{
cout << "Please enter the mass in Kg: ";
float mass //this is line 16
cin >> mass; // user inputs value of mass in Kg
if (mass<=0) //error checking make sure the value of
{ //mass is great than zero
cout << "Please try again and enter a positive number."
<< endl;
return 0;
}
float energy;
energy=mass * pow (LIGHT_SPEED,2);
cout << "The energy is " << energy << 'n';
}
© 1998, 2010 by Lindsey Anderson. All Rights Reserved.
Don’t worry if you don’t understand the program; you’re not expected to at this point. We’re going
to spend the next few chapters deconstructing this program, piece by piece, so that you can fully
understand it.
Programming and Algorithms
This program is typical of ones that you will write as a programmer. You don’t need to know the
science, financial theory, or whatever that underlies the program; you just need to know the
algorithm.
We’ve all been familiar Einstein’s famous equation, E=mc2
, since we were kids. But if you’re like
me, you don’t understand the theory of relativity. You don’t need to, to write the program above.
You just need to know that some variable Energy is equal to the mass times the speed of light
squared.
Simply put, an algorithm is a systematic solution to a problem. It can take the form of a simple
equation like above, or it can take the form of several equations, or several equations and various
new variables. As long as there is a systematic way to get form point A to point B you have an
algorithm.
You’re not always expected, as a beginning programmer, to come up with the algorithm yourself.
Many times the algorithm will be given to you by the people requesting the program.
But as you progress as a programmer, you will be responsible more and more for the algorithm
yourself. An experienced programmer spends most of his or her time figuring out algorithms. Once
you have the algorithm, the code should more or less write itself.
There are two techniques figuring out algorithms. First you can write an outline, in English,
describing how you want the program to work. If you can’t find the words to describe what you want
your program to do, you haven’t figured out the algorithm yet. The second approach is called
stepwise refinement. We’ll cover both of these approaches in later chapters.
Compiling and Debugging
Before we start taking our program apart, piece-by-piece, perhaps we should run it first to make sure
it works. Here we encounter the first snag. The computer doesn’t understand our program, also
known as the source code, any better than you do. As far as the computer is concerned our source
code is just another word processing document, no different than a letter to Mom.
Computers run on a series of zeros and ones called machine language. Before we can run our
program we need to convert our source code into machine language. That’s what compilers do. They
take higher level, C++ programming code that can be written and understood by human beings, and
convert it into executable machine language.
Mac, Windows and UNIX computers have different types of CPUs and therefore use different types
of machine languages. So they each require their own compiler. Make sure you get a compiler that
will generate machine code for your computer.
You may have heard C++ being referred to as an Object Oriented Program. One of the advantages of
OOPs is that the same code can be used on different computer platforms. Our program will run on
Mac, Windows, and UNIX computers without any changes. It just has to be compiled three times,
once on each platform.
While you need a compiler to run the program you don’t need a special program to write it. You can
use any word processor. You just need to be able to move the program from your word processor
© 1998, 2010 by Lindsey Anderson. All Rights Reserved.
into the compiler. You can do this by either copy and pasting or by saving your word processor file
as text and importing the text file into your compiler, assuming that it can import text.
You’re only going to be using a word processor to write your source code when you’re using a
public domain compiler like gnu++. If your using a modern commercial compiler, then it will (or
you shouldn’t buy it) have a built in text editor. The built in text editor is better than a word
processor because it helps you avoid errors by automatically indenting your blocks of code and
making sure every brace and parenthesis has a match.
You should be aware that there may be variations from one compiler to another. The C++ language
is not static. Like your word processor or your spreadsheet, there are periodic improvements. Every
few years a group, the ANSI standards committee, gets together and reviews and approves changes
in the C++ language. If your source code incorporates the latest and greatest features, it may not
compile with an older compiler. All the concepts covered in this book are standard and have been
around for a while so they should compile just fine.
When we are compiling a program we are creating a separate and independent file that contains the
machine code. It is a common practice to give the executable file a name similar to the program
name with the extension, .exe, to identify it as the executable file. The .exe extension is helpful but
not absolutely necessary. In summary, then, when we say we are running the program, we are not
actually running the program (the source code) per se; we are running the executable file.
Compiling is a three step process: preprocessor, object, and linking. During the preprocessor stage
the compiler looks for the #include command. If it can’t find #include then it moves directly to the
object stage.
This #include command alerts the preprocessor that there are libraries that our program needs to
reference in order to generate executable code. Our program uses two libraries, iostream.h and
math.h.
We will cover libraries in more detail later but here’s the quick and dirty. Why reinvent the wheel?
Libraries have code that can be used by many programs. It is much easier to include the library than
to rewrite the same code a million times. Furthermore the quality of the code in a library will be
better than what you would write yourself because it has been optimized for speedy performance.
The preprocessor stage looks for included libraries but does not incorporate their code into an
executable file at this point. The preprocessor stage is just concerned with whether the compiler can
find the libraries. The actually incorporating of the library code occurs in the linking stage. If the
compiler can’t find the libraries you will get an error message to that effect.
In the object stage the compiler generates the machine language for the executable file. Before it
makes the conversion it first checks your source code to make sure there are no syntax or lexical
errors. We will define syntax and lexical errors shortly. If there are errors, the compiler will give you
an appropriate error message and not generate machine code. You must then debug your errors and
try compiling again.
Once the compiler successfully generates the object code then it incorporates the links from the
libraries into the executable code. The linked files are already in machine language so we don’t have
to worry about converting the links into machine language.
Back in the late 1980’s, the C++ stone age, compiling and linking were distinct operations that you
had to do separately. First you would use the compiler generated a separate object file. Then you
would run a separate program called a linker, similar to a compiler, on the object file to incorporate
the linked library files into the object code so that you could create an execution file.
© 1998, 2010 by Lindsey Anderson. All Rights Reserved.
Modern compilers combine the compiling and linking functions into the compiler. In theory the
compiler still creates a separate object file but you never see it or have any control over it. The
compiler automatically links the libraries to the object file and generates the executable file. The
reason for this history lesson is that you could have an old C++ program that requires separate steps
for compiling and linking.
So much for background, now lets compile our program. When we do so, we get the following error
message:
our_program.cc: In function `int main(...)':
our_program.cc:16: parse error before `>'
What we have here is a bug in the form of a syntax error. Syntax errors are errors in grammar or
punctuation. There should be a semi-colon after mass on line 16. We will spend a great deal of time
discussing the grammar and punctuation of C++ as we go along.
Syntax errors are not the only kind of bug we will encounter. There are also lexical, execution, and
intent errors. Lexical errors occur when our program contains a word or words that is not in the C++
vocabulary. The C++ language has a series of key words, like “if”, that it automatically understands.
If you misspell a keyword, or if you fail to define a variable before using it, you will get a lexical
error that will produce an error message.
Execution errors occur after the program has been compiled. If you ever used a computer, you’ve
experienced an execution error. Everything seems to be running just fine, until suddenly the
computer bombs. There is nothing a compiler can do to help you avoid execution errors. You just
have to make sure you include error checking and fool proofing as you write your program. We’ll
discuss how to do this in future chapters.
Finally we could have an error of intent. Intent error mean that the program compiles and runs fine,
but does not give the correct answer. For example, if we had POW (LIGHT-SPEED,3) instead of
POW (LIGHT-SPEED,2) in our program, everything would work just fine except we would get the
wrong answer.
Now that we have fixed the syntax error by putting a semi-colon after float mass, lets run the
program and see what we get:
Please enter the mass in Kg: 15
The energy is 1.34801e+18
When we enter in a positive number for mass and:
Please enter the mass in Kg: -25
Please try again and enter a positive number.
when we enter in a negative. So our error checking is working fine. In the examples above the items
we inputted from the keyboard are underlined.
When we run the program we get the message to
Please enter the mass in Kg:
The computer then pauses waiting for us to input from our keyboard the amount of mass. The
computer will continue to pause and pause and pause until the amount for mass is entered. So the
user has to be alert. Once the mass has been imputed the computer outputs the amount of energy
converted from the mass.
© 1998, 2010 by Lindsey Anderson. All Rights Reserved.
Comments
Now lets take a look at the various parts or the program. The first thing we see in our program is:
/* This program uses Einstein’s famous equation, E=mc2
, from his
Theory of Relativity to convert a given mass (in kilograms)
into energy */
This is a comment that explains what the program does. You should always start your program with
a similar statement.
The ideal of C++ is to write once and use many times. No one else is going to be able to use your
code unless they know what it does. And if you’re like me, six months after you’ve written your
code, you’ll have no idea what it does unless you used comments.
It is not enough just to comment what the program does. You must also explain how it works. Weeks
or months down the road you, your coworkers, or your successor may encounter a problem similar to
the one solved by your program. The easiest way to solve a similar problem is to modify a program
you’ve already written. But if you don’t use comments to explain your code, no one, including
yourself, is going to be able to figure out your code quickly enough to make modifying worthwhile.
It will be faster just to write new code.
When you write a program you will test and debug before implementing. Unfortunately it may take
months, even year, for some bugs to surface. So the most important reason for commenting your
code is because you or someone else may have to debug it months or years after its implementation.
If you are studying C++ in an academic environment, you will find that the most difficult test
questions will be those where you have to debug some else’s code. Of course there are never any
comments! As those precious minutes slip away, and you stare at the incomprehensible and
convoluted code, you’ll wish that there were just a few comments. Don’t make yourself or anyone
else suffer this agony, make sure you comment your code!
Comments are for human beings; they never get compiled. When the compiler sees a comment it
ignores it.
There are two ways to write comments. You can enclose your comments in /* */ pairs between
which you can write as much as you want or you can comment a single line with //. The // approach
is limited to a single line. If the comment goes beyond a line like this:
if (mass<=0) //error checking make sure the value of
mass is greater than zero
then your program will not compile because the compiler will think that is, greater, than,
and zero are undeclared variables.
There are two common errors beginning programmers make around comments. It is easy to start a
long comment with /* and then forget to close with */. If you forget to close the comment then the
compiler will interpret the whole program as being a comment and nothing will happen.
We already covered the other common error of letting comments preceded by a // to go beyond a
single line. Of course, you can work around the one line rule by using // on the second line. We did
this in our program above.
© 1998, 2010 by Lindsey Anderson. All Rights Reserved.
Indents and Blocks
Lets take look at our program’s structure:
/* This program uses Einstein’s famous equation, E=mc2
, from his
Theory of Relativity to convert a given mass (in kilograms) into
energy */
#include <iostream.h> //library containing cin, cout,
//<<, & >>
#include <math.h> //library containing power function pow()
const float LIGHT_SPEED=2.9977925e8;
/* declaring constant for speed of light in meters/sec */
float main()
{
cout << "Please enter the mass in Kg: ";
float mass; //this is line 16
cin >> mass; // user inputs value of mass in Kg
if (mass<=0) //error checking make sure the value of
{ //mass is great than zero
cout << "Please try again and enter a positive number."
<< endl;
return 0;
}
float energy;
energy=mass * pow (LIGHT_SPEED,2);
cout << "The energy is " << energy << 'n';
}
Notice that everything is aligned on the left margin until we get to the main () function. Everything
within the main function is enclosed within a left brace, {, and a right brace, }.
Everything between left and right braces is known as a block. Blocks are a visual clue that a group of
code goes together. To even enhance this visual effect, it is good programming practice to indent the
code within a block, as we did with the main() block.
There is an important difference between braces and indents. Braces are required syntax while
indents are not. Our program would be harder to read without indents, but it would still work.
Without the braces the program would never compile.
Here are some key points on brace syntax. Make use you use the curly braces {}, and not the square
brackets []. Braces are always a match set. Don't forget the end brace, }.
© 1998, 2010 by Lindsey Anderson. All Rights Reserved.
We can have as many blocks are we need within a program. In our example we also have the
statement:
if (mass<=0) //error checking make sure the value of
{ //mass is great than zero
cout << "Please try again and enter a positive number."
<< endl;
return 0;
}
The block:
{ //mass is great than zero
cout << "Please try again and enter a positive number."
<< endl;
return 0;
}
is part of the if statement that is within the main() block. Notice that it is indented even more than
the rest of the main() block. Once again this additional indenting is good programming practice but it
is not necessary for the program to run.
Libraries
The C++ language is designed to be modular. Not all the required functionality is within the
language itself. Libraries like iostream.h and the math.h are need for additional
functionality or ease of use.
The iostream library adds input/output capability. Without iostream we would not get the request to
"Please enter the mass in Kg: " or have the opportunity to enter a value into the
variable mass.
We need the math.h library to use the pow function. However, in our example, the math.h library is
providing ease of use rather than required functionality because we could have just as easily written
our equation as energy=mass * LIGHT_SPEED * LIGHT_SPEED.
Of course, if we had a program that raised the power of LIGHT_SPEED to 1,000, we would justify
the use of the math library on grounds of functionality and not ease of use. No responsible
programmer is going to put * LIGHT_SPEED a thousand times. How would anyone check it for
errors? Instead a responsible programmer would use the pow function, pow (LIGHT_SPEED,1000),
because it provides necessary functionality. Its hard to put your finger on exactly where, but at some
point, easy of use gives way to functionality.
The pow function is just one of the many functions built into the math.h library. Others in include
absolute value, floor, ceiling, and the like. While the grammar is different, these built in functions
are similar in concept to the built in functions in Microsoft Excel and other spreadsheets. Later in
this book we will describe what some of these other functions do and how to use them.
The iostream.h and the math.h libraries are just two of many. Other libraries include ctype.h, time.h,
and iomanip.h. While these particular libraries are so common that you can expect them to be
available with your C++ program, don’t assume that every library you may find in a reference book
will be available. To find out if an interesting library is available, you either have to check the
documentation of your software or just include the library in a program and see if the compiler finds
it.
© 1998, 2010 by Lindsey Anderson. All Rights Reserved.
During the precompile stage the compiler needs to be able to find the libraries. Generally, when your
C++ program is installed, it places the common libraries in the same folder or directory as the
compiler itself. Consequently the compiler has no trouble finding the libraries. If you have C++ on
your personal computer, be careful not to throw out or move the libraries, or your compiler will not
find them.
Thus far we have been talking about the built in libraries. You can also create your own libraries.
We’ve mentioned the goal of write once use many times. If you have written code that you want to
use again in another program you would create a library to hold that code and then include the
library within the other program. For example, if our program had some code that used the library
goodies.h, we would have had the statement #include <goodies.h> along with #include <iostream.h>
and #include <math.h>. You will learn how to create your own libraries at the end of the book when
we cover Classes.
Here is some of the syntax of Libraries. They are always called in the beginning of the program with
the keyword #include. The name of the library is always within angle brackets, <>.
Have you noticed that all our libraries have the suffix .h? The .h refers to header. The header file just
has the declarations of the various functions. The details reside in another file. When we get to the
chapter on Classes, this will make more sense.
Earlier we discussed ANSI standards. One of the improvements of the latest ANSI meeting was to
eliminate the .h in the most common library headers. Your compiler may or may not have
incorporated this change. Try #include<iostream> without the .h in a program. If it works, fine, if
not put back the .h. We will continue to use the .h throughout this book.
Variables
You have been using variables since high school algebra, if not before. We can rewrite Einstein’s
formula in the more familiar algebraic form:
y=(8.98676e16)x
Here y is the energy, x is the mass and the constant, LIGHT_SPEED squrared, is replaced with its
actual value.
In our program we have the variables energy and mass but we are also treating the constant,
LIGHT_SPEED, as a variable. We don’t have to treat constants like variables. We could have used:
energy=mass * (8.98676e16)
but we would have lost the instant recognition of Einstein equation. LIGHT_SPEED squared is more
obvious.
The first step in using a variable is to declare it by identifing the variable type as well as its name.
When we declared LIGHT_SPEED,
const float LIGHT_SPEED=2.9977925e8;
we said was of type float. We also said that mass and energy were of type float. Float is one of the
two most common variable types but there are many more. We will cover other variable types in
future chapters.
When we declared LIGHT_SPEED we immediately initialized it. Initialization is the process of
giving variables a value.
There are three ways to initialize a variable. First we can make the initial value part of the
declaration as we did with LIGHT_SPEED. Secondly we can initialize the variable from the
© 1998, 2010 by Lindsey Anderson. All Rights Reserved.
keyboard as we did with mass. Finally we can initialize a variable with a formula like we did with
energy.
If you use this last approach make sure you initialize all the other variables in the formula first. If
mass and LIGHT_SPEED hadn’t already been initialized, we would have gotten an error message
during compiling.
Variables are the backbone of each and every program. They are the most important objects of
object oriented programming. Without variables we wouldn’t have computers. We are going to
spend the next chapter exclusively on variables. We will also discuss other types of variables in
future chapters.
Input/Output
This is the process by which we get information in and out of the program. We already discussed the
need for the iostream.h library. This library adds the functionality of cout, cin, <<, & >>.
Output is a function of cout (pronounced see-out). When we want the computer to output a message
we use a statement like:
cout << "Please enter the mass in Kg: ";
Whenever we want the program to print something on our computer monitor we start the statement
with cout and follow it with the output operator, <<.
The statement itself must be within straight quotes ("…") not curly quotes (“…”). VERY
IMPORTANT: If your are writing your program on a modern word processor like Microsoft Word,
you need to either turn off the smart quote feature or use the copy and paste to replace the curly
quotes with straight quotes. You will get an error message when you compile using curly quotes.
The statement must be limited to one line and it must conclude with a semi-colon. The way around
the single line rule is to use multiple output operators. Here’s an example:
cout << "This program uses Einstein’s famous equation,"
<< "E=mc2
, from his Theory of Relativity to "
<< "convert a given mass (in kilograms) into"
<< " energy";
Notice that the semi-colon does not appear until the very end. However each line must end with a
straight quote, and, after the first line, each line must start with the output operator, <<. We only
need to use cout once. It is good programming practice to align all the output operators one on top of
the other. Also notice either at the end of the line or at the beginning of the next line there is a space
before or after the straight quote. Without that space the lines will run together like so:
This program uses Einstein’s famous equation,E=mc2
, from his
Theory of Relativity toconvert a given mass (in kilograms)
intoenergy
Finally, as in the case above, what actually outputs on the screen may not have the same line breaks
as it did when you wrote the cout statement in your program.
Use cin (pronounced see-in) for input along with the input operator, >>. You will use cin to input the
values of variables directly into the program. In our example we used cin to input the value of mass.
As long as we keep inputting numbers, one after another, they all will be part of the value of the
variable. The way we tell the computer we are done inputting the value of the variable is to hit enter,
return, or space on our keyboard.
© 1998, 2010 by Lindsey Anderson. All Rights Reserved.
Once you’ve made a commitment, via your program, to enter a value into a variable, you must do so.
The program will hang until you enter your value and will continue to hang until you give it the
signal that you’re done with the entry.
When you give the signal that you are done with the data entry, the computer will automatically
move to the next line on the screen. But it will not do so for screen output unless the line is full. To
move screen output to the next line use the command, endl.
Its easy to get the << and >> operators mixed up. Here’s an easy mnemonic devise. If the arrows are
pointing into the page, >>, they are the input operator. If the arrows are pointing away, out of the
page they are the output operator.
main()
Every C++ program has one and only one main function. That’s where the meat is. A main function
always has the parentheses, (), following main, main(), and a starting brace and an ending brace. It
its good programming practice to indent all the contents of a main function to make it easy to tell
where the main function starts and where it ends.
Everything outside the main function is support material. In our program the libraries and the
declaration of the LIGHT_SPEED constant are all supporting the main function. As you become
more comfortable with C++ programming, you will start writing your own functions. These too must
be declared outside of the main function.
Notice that the main function was declared to be of the type float, float main(). You want to declare
the main function to be the same type as the variable it returns. Since our program returns the float,
energy, we declare our main function to be float. We will discuss types more in the chapter on
variables.
Sometimes your main function may return several variables of different types. If one of those
variables is an integer, then declare int main(). Otherwise just choose one of the variable types and
declare your main function accordingly. Even though you may return more than one variable type
within a main function, a main function can be of only one type.
Sometimes a main function does not return a variable at all. In that case declare the main function as
void, void main(). Some programmers will declare all main functions as void and the program will
work even if it is returning integer and/or other variables. However this is not considered good
programming practice.
Decision Making
In our program we do not want to return a value for energy, if a negative number were entered into
mass. To avoid this we used an if statement to insure that the mass is positive.
The if statement enables us to make a decision. The program does one thing if the test is true and
nothing if the test is false. In our program the if statement tests to see if mass is negative or equal to
zero. If the mass is not positive then the program tells us to enter in a positive number and stops. If
mass is indeed positive, our program continues with the rest of the code.
Here’s a tip to save you hours of hair pulling agony. The proper syntax of an if statement is if (test
goes here). Notice that if is with a small i not a capital I. Every beginning programmer makes the
mistake of using If instead of if.
All forms of decision making, not just the if statement, have a test. The test must be Boolean, either
true or false. In our program the test is mass<=0. The program inserts the value of mass into the test
© 1998, 2010 by Lindsey Anderson. All Rights Reserved.
and makes a determination if it is true or not. Clearly -25 is less than or equal to zero, so when -25
was entered into mass our if statement was true and the program halted.
Because computers are based on a binary series of ones and zeros, it is a convention to define true as
1 and false as 0. However the more rigorous definition is that 0 is false and all other numbers are
true. Consequently, while the statement, if (5), has no meaningful test, it will always be true.
Lets take another look at our if statement:
if (mass<=0) //error checking make sure the value of
{ //mass is great than zero
cout << "Please try again and enter a positive number."
<< endl;
return 0;
}
Notice that the test is always in parenthesis and that there is no semi-colon after the last parenthesis.
If there is more than one line of code to be executed if the test is true, it is common to move the
statement to the next line and enclose it in blocks like as done above. Here the braces are required
because the things to do, if true, take up several lines of code.
If the true response was just one line we don’t really need the braces or even a separate line. For
instance this perfectly acceptable and even preferred:
if (test) do this single line of code;
Notice that there is still no semi-colon after the last parenthesis of the test but that there is one at the
end of the line of code.
Our if statement is just one of many ways, including nested if statements, of making a decision. We
will spend considerable time on decision making later in this book.
Error Checking: Garbage in, Garbage out
In our problem we used the if statement for error checking. We wanted to avoid negative mass
because there is no such thing as negative energy (ignoring anti-matter).
The if statement is not the only form of error checking. If we included the assert.h library, we could
have used the assert(mass>0) function. If the test is false, then assert automatically halts the program
and returns the computer to the control of the operating system. However, assert is not as useful as
the if statement for error checking because assert just quits without telling us why. Our if statement
tells us why the program quit.
We will cover other methods of checking errors as we go along. You must realize that it is your
responsibility to idiot proof your program. You have to expect that users, either on purpose or by
mistake, will try to enter data that will cause errors. You must do your best to anticipate such errors
and write code that will preserve the operation of your program even when the user makes a mistake.
In our program we were only half successful in anticipating user errors. While we guarded against
the user entering in a negative number, we did not anticipate the user entering text rather than a
number. If the user typed the word, five, instead of the number 5, our program would have crashed.
We will cover how to handle this kind of error later in the book.
return 0
When we had negative mass, we used the statement, return 0;, to quit our program. You can use
return 0 to quit any program; so you must be judicious in its use. Only use return 0 when you want to
© 1998, 2010 by Lindsey Anderson. All Rights Reserved.
terminate a program midstream. Don’t use it to end a program; the ending brace, }, of the main()
function will do that.
The statement, return 0, is not the only case in which you will use the keyword, return. You will use
return later, when you start creating your own functions and Boolean expressions.
Keywords
There are certain words in C++, known as keywords, that have special meaning to C++. Here is a list
of those words:
asm namespace
auto new
bool operator
break private
case protected
catch public
char register
class reinterpret_cast
const return
const_cast short
continue signed
default sizeof
delete static
do static_cast
double struct
dynamic_cast switch
else template
enum this
explicit throw
extern true
false try
float typedef
for typeid
friend typename
goto union
if unsigned
inline using
int virtual
long void
mutable volatile
while
Do not use these words as variables or for anything else other than their predefined meaning. We
have already touched upon the meanings of if and return. We will cover many, but not all, of the
other keywords as we go along.
In addition to keywords there are other words that are what we will call special. Notice that our list
of keywords does not include cout, cin, or endl. These words became special when you use the
iostream.h library. Once you have included the iostream.h library you can not use these words for
variables; but you can use them as variables if you have not included the iostream library.
© 1998, 2010 by Lindsey Anderson. All Rights Reserved.
Keywords and special words are all case sensitive. We already pointed out that If is not the same
thing as if. Since all the keywords and special words are all in lower case, use only lower case when
using them.
Arithmetic Operators
Einstein’s equation, E=mc2
, will not work directly in C++. The C++ language does not fully follow
the rules of algebra that you learned in high school. The compiler would perceive mc2
as the
undeclared variable, mc2.
You can not assume arithmetic operators, like multiplication, by putting two or more variables next
to each other, as in mc2
. Operators must be explicit. In this case the explicit operator is the same *
you use on a pocket calculator.
Neither does C++ recognize algebraic conventions for exponents. That is why the mc2
of Einstein’s
equation becomes the undeclared variable mc2. You must use the pow function or spell out the
multiplication (c * c).
In Einstein’s equation the = sign means equal, but in C++ the = sign is the assignment operator. The
equals sign is ==. In our example this distinction is so subtle that it is practically lost. In our program
we are not saying that Energy is equal to mass * pow (LIGHT_SPEED,2); we are saying that the
variable, Energy, is being assigned (or gets) the value of mass * pow (LIGHT_SPEED,2).
Why bother with this distinction when the outcome is the same? Because the outcome is not always
the same. Here are two examples where the outcomes are very different. There are times when you
may want to keep track of how many times a certain event occurs, so you declare a variable, counter.
Every time the event occurs you want to advance the counter by 1. You would do it like so:
counter=counter+1
Now clearly counter cannot be equal to itself plus 1; yet this is a valid C++ expression. What it
means is take the old value of counter and add 1 to it and then replace the old value of the counter
with the new. For example if our counter had a value of 5 and if another instance of the event we are
counting occurred, we would assign counter the value of the old counter, 5, plus 1, for a new value
of 6.
Here’s another example. Suppose you were doing something with weights that required special
handling when the weight equaled 100. If you used the expression:
if (weight=100)
you would always perform the special handling because the expression, (weight=100), would,
regardless of the original value of weight, set weight equal to 100. The proper expression is:
if (weight==100)
Here special handling would be required only if the value of weight were equal to 100.
There are many other instances where C++ does not adhere to the conventions of algebra. We will
cover those instances in the chapter on operators.
Good Programming Practice
We have made reference several times to good programming practice and we will continue to do so
throughout this book. Good programming practice is nothing more than good programming
conventions or habits.
© 1998, 2010 by Lindsey Anderson. All Rights Reserved.
Good programming practice is not the same thing as syntax. Ignore the rules of syntax and your
program will fail to run. Ignore good programming practices and your program will run but it may
be harder to read and understand.
Remember the whole point of using an object oriented programming language like C++ is to make it
easier to you and others to reuse code whenever possible. Failure to use good programming practice
undermines OOPs by making it harder to recycle code.

More Related Content

What's hot

Laporan Praktikum Sistem Operasi Modul 9 dan 10
Laporan Praktikum Sistem Operasi Modul 9 dan 10Laporan Praktikum Sistem Operasi Modul 9 dan 10
Laporan Praktikum Sistem Operasi Modul 9 dan 10Indah Kusumawati
 
Pancasila sebagai ideologi negara
Pancasila sebagai ideologi negaraPancasila sebagai ideologi negara
Pancasila sebagai ideologi negarainasalsa
 
Materi matakuliah bahasa c
Materi matakuliah bahasa cMateri matakuliah bahasa c
Materi matakuliah bahasa cIzhan Nassuha
 
Presentasi TIK POWER POINT
Presentasi TIK POWER POINTPresentasi TIK POWER POINT
Presentasi TIK POWER POINTnoviaNP
 
Membuat grafik sederhana pada java dengan JFreeChart
Membuat grafik sederhana pada java dengan JFreeChartMembuat grafik sederhana pada java dengan JFreeChart
Membuat grafik sederhana pada java dengan JFreeChartAgung Sulistyanto
 
Makalah Peran Generasi Muda Dalam Wujud Bela Negara
Makalah Peran Generasi Muda Dalam Wujud Bela NegaraMakalah Peran Generasi Muda Dalam Wujud Bela Negara
Makalah Peran Generasi Muda Dalam Wujud Bela NegaraMudhoffar Syarif
 
Pancasila dalam konteks sejarah perjuangan bangsa indonesia
Pancasila dalam konteks sejarah perjuangan bangsa indonesiaPancasila dalam konteks sejarah perjuangan bangsa indonesia
Pancasila dalam konteks sejarah perjuangan bangsa indonesiaYabniel Lit Jingga
 
Modul PBO Bab-02 - Struktur Kontrol
Modul PBO Bab-02 - Struktur KontrolModul PBO Bab-02 - Struktur Kontrol
Modul PBO Bab-02 - Struktur KontrolRakhmat Dedi Gunawan
 
Pancasila dalam sejarah perjuangan bangsa indonesia
Pancasila dalam sejarah perjuangan bangsa indonesiaPancasila dalam sejarah perjuangan bangsa indonesia
Pancasila dalam sejarah perjuangan bangsa indonesiaUnique Hartianti
 
190036587 makalah-demokrasi-dalam-islam
190036587 makalah-demokrasi-dalam-islam190036587 makalah-demokrasi-dalam-islam
190036587 makalah-demokrasi-dalam-islamcaturprasetyo11tgb1
 
Perancangan database penyewaan lapangan
Perancangan database penyewaan lapanganPerancangan database penyewaan lapangan
Perancangan database penyewaan lapanganevi kufia mahasanti
 
Sistem politik islam dan demokrasi
Sistem politik islam dan demokrasi Sistem politik islam dan demokrasi
Sistem politik islam dan demokrasi atuulll
 
Contoh Screenshot Ragam Dialog Interaktif
Contoh Screenshot Ragam Dialog Interaktif Contoh Screenshot Ragam Dialog Interaktif
Contoh Screenshot Ragam Dialog Interaktif naufals11
 

What's hot (20)

Kompilasi13 ka p (1)
Kompilasi13 ka p (1)Kompilasi13 ka p (1)
Kompilasi13 ka p (1)
 
Pancasila dan liberalisme
Pancasila dan liberalismePancasila dan liberalisme
Pancasila dan liberalisme
 
Laporan Praktikum Sistem Operasi Modul 9 dan 10
Laporan Praktikum Sistem Operasi Modul 9 dan 10Laporan Praktikum Sistem Operasi Modul 9 dan 10
Laporan Praktikum Sistem Operasi Modul 9 dan 10
 
Dasar dasar coreldraw 1
Dasar dasar coreldraw 1Dasar dasar coreldraw 1
Dasar dasar coreldraw 1
 
Pancasila sebagai ideologi negara
Pancasila sebagai ideologi negaraPancasila sebagai ideologi negara
Pancasila sebagai ideologi negara
 
Materi matakuliah bahasa c
Materi matakuliah bahasa cMateri matakuliah bahasa c
Materi matakuliah bahasa c
 
Presentasi TIK POWER POINT
Presentasi TIK POWER POINTPresentasi TIK POWER POINT
Presentasi TIK POWER POINT
 
Membuat grafik sederhana pada java dengan JFreeChart
Membuat grafik sederhana pada java dengan JFreeChartMembuat grafik sederhana pada java dengan JFreeChart
Membuat grafik sederhana pada java dengan JFreeChart
 
Makalah Peran Generasi Muda Dalam Wujud Bela Negara
Makalah Peran Generasi Muda Dalam Wujud Bela NegaraMakalah Peran Generasi Muda Dalam Wujud Bela Negara
Makalah Peran Generasi Muda Dalam Wujud Bela Negara
 
Pancasila dalam konteks sejarah perjuangan bangsa indonesia
Pancasila dalam konteks sejarah perjuangan bangsa indonesiaPancasila dalam konteks sejarah perjuangan bangsa indonesia
Pancasila dalam konteks sejarah perjuangan bangsa indonesia
 
Modul PBO Bab-02 - Struktur Kontrol
Modul PBO Bab-02 - Struktur KontrolModul PBO Bab-02 - Struktur Kontrol
Modul PBO Bab-02 - Struktur Kontrol
 
Laporan
LaporanLaporan
Laporan
 
Pancasila dalam sejarah perjuangan bangsa indonesia
Pancasila dalam sejarah perjuangan bangsa indonesiaPancasila dalam sejarah perjuangan bangsa indonesia
Pancasila dalam sejarah perjuangan bangsa indonesia
 
190036587 makalah-demokrasi-dalam-islam
190036587 makalah-demokrasi-dalam-islam190036587 makalah-demokrasi-dalam-islam
190036587 makalah-demokrasi-dalam-islam
 
Modul lengkap
Modul lengkapModul lengkap
Modul lengkap
 
Makalah rule of law
Makalah rule of lawMakalah rule of law
Makalah rule of law
 
Perancangan database penyewaan lapangan
Perancangan database penyewaan lapanganPerancangan database penyewaan lapangan
Perancangan database penyewaan lapangan
 
Sistem politik islam dan demokrasi
Sistem politik islam dan demokrasi Sistem politik islam dan demokrasi
Sistem politik islam dan demokrasi
 
Contoh Screenshot Ragam Dialog Interaktif
Contoh Screenshot Ragam Dialog Interaktif Contoh Screenshot Ragam Dialog Interaktif
Contoh Screenshot Ragam Dialog Interaktif
 
TEKNIK ENKRIPSI DAN DEKRIPSI HILL CIPHER
TEKNIK ENKRIPSI DAN DEKRIPSI HILL CIPHERTEKNIK ENKRIPSI DAN DEKRIPSI HILL CIPHER
TEKNIK ENKRIPSI DAN DEKRIPSI HILL CIPHER
 

Similar to Programming in C++

His162013 140529214456-phpapp01
His162013 140529214456-phpapp01His162013 140529214456-phpapp01
His162013 140529214456-phpapp01Getachew Ganfur
 
What every C++ programmer should know about modern compilers (w/ comments, AC...
What every C++ programmer should know about modern compilers (w/ comments, AC...What every C++ programmer should know about modern compilers (w/ comments, AC...
What every C++ programmer should know about modern compilers (w/ comments, AC...Sławomir Zborowski
 
C plus plus for hackers it security
C plus plus for hackers it securityC plus plus for hackers it security
C plus plus for hackers it securityCESAR A. RUIZ C
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verQrembiezs Intruder
 
Chapter 2 Program language translation.pptx
Chapter 2 Program language translation.pptxChapter 2 Program language translation.pptx
Chapter 2 Program language translation.pptxdawod yimer
 
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdfINTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdfSubramanyambharathis
 
C++ In One Day_Nho Vĩnh Share
C++ In One Day_Nho Vĩnh ShareC++ In One Day_Nho Vĩnh Share
C++ In One Day_Nho Vĩnh ShareNho Vĩnh
 
An introduction to programming
An introduction to programmingAn introduction to programming
An introduction to programmingrprajat007
 
Compliers and interpreters
Compliers and interpretersCompliers and interpreters
Compliers and interpretersshivasdhtsvmic
 
Comso c++
Comso c++Comso c++
Comso c++Mi L
 
CS8251_QB_answers.pdf
CS8251_QB_answers.pdfCS8251_QB_answers.pdf
CS8251_QB_answers.pdfvino108206
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++KurdGul
 
Software programming and development
Software programming and developmentSoftware programming and development
Software programming and developmentAli Raza
 
Chapter1pdf__2021_11_23_10_53_20.pdf
Chapter1pdf__2021_11_23_10_53_20.pdfChapter1pdf__2021_11_23_10_53_20.pdf
Chapter1pdf__2021_11_23_10_53_20.pdfDrIsikoIsaac
 

Similar to Programming in C++ (20)

C++ for hackers
C++ for hackersC++ for hackers
C++ for hackers
 
His162013 140529214456-phpapp01
His162013 140529214456-phpapp01His162013 140529214456-phpapp01
His162013 140529214456-phpapp01
 
What every C++ programmer should know about modern compilers (w/ comments, AC...
What every C++ programmer should know about modern compilers (w/ comments, AC...What every C++ programmer should know about modern compilers (w/ comments, AC...
What every C++ programmer should know about modern compilers (w/ comments, AC...
 
C plus plus for hackers it security
C plus plus for hackers it securityC plus plus for hackers it security
C plus plus for hackers it security
 
Tutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng verTutorial basic of c ++lesson 1 eng ver
Tutorial basic of c ++lesson 1 eng ver
 
Chapter 2 Program language translation.pptx
Chapter 2 Program language translation.pptxChapter 2 Program language translation.pptx
Chapter 2 Program language translation.pptx
 
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdfINTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
 
C++ In One Day_Nho Vĩnh Share
C++ In One Day_Nho Vĩnh ShareC++ In One Day_Nho Vĩnh Share
C++ In One Day_Nho Vĩnh Share
 
An introduction to programming
An introduction to programmingAn introduction to programming
An introduction to programming
 
Cp week _2.
Cp week _2.Cp week _2.
Cp week _2.
 
Compliers and interpreters
Compliers and interpretersCompliers and interpreters
Compliers and interpreters
 
Comso c++
Comso c++Comso c++
Comso c++
 
CS8251_QB_answers.pdf
CS8251_QB_answers.pdfCS8251_QB_answers.pdf
CS8251_QB_answers.pdf
 
How a Compiler Works ?
How a Compiler Works ?How a Compiler Works ?
How a Compiler Works ?
 
C lecture notes new
C lecture notes newC lecture notes new
C lecture notes new
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
 
C
CC
C
 
The basics of c programming
The basics of c programmingThe basics of c programming
The basics of c programming
 
Software programming and development
Software programming and developmentSoftware programming and development
Software programming and development
 
Chapter1pdf__2021_11_23_10_53_20.pdf
Chapter1pdf__2021_11_23_10_53_20.pdfChapter1pdf__2021_11_23_10_53_20.pdf
Chapter1pdf__2021_11_23_10_53_20.pdf
 

Recently uploaded

Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 

Recently uploaded (20)

Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 

Programming in C++

  • 1. © 1998, 2010 by Lindsey Anderson. All Rights Reserved. Introduction to Programming in C++ By Lindsey Anderson I wrote 4 chapters of an unpublished book on Programming in C++. The following Chapter 1 is presented here to demonstrate my ability to describe complex material in a simple, straightforward manner. 1 Introduction & Overview The best way to learn a foreign language, some sages say, is to totally immerse yourself in the language. We are going to use the total immersion technique with C++. Take a look at the following program: /* This program uses Einstein’s famous equation, E=mc2 , from his Theory of Relativity to convert a given mass (in kilograms) into energy */ #include <iostream.h> //library containing cin, cout, //<<, & >> #include <math.h> //library containing power function pow() const float LIGHT_SPEED=2.9977925e8; /* declaring constant for speed of light in meters/sec */ float main() { cout << "Please enter the mass in Kg: "; float mass //this is line 16 cin >> mass; // user inputs value of mass in Kg if (mass<=0) //error checking make sure the value of { //mass is great than zero cout << "Please try again and enter a positive number." << endl; return 0; } float energy; energy=mass * pow (LIGHT_SPEED,2); cout << "The energy is " << energy << 'n'; }
  • 2. © 1998, 2010 by Lindsey Anderson. All Rights Reserved. Don’t worry if you don’t understand the program; you’re not expected to at this point. We’re going to spend the next few chapters deconstructing this program, piece by piece, so that you can fully understand it. Programming and Algorithms This program is typical of ones that you will write as a programmer. You don’t need to know the science, financial theory, or whatever that underlies the program; you just need to know the algorithm. We’ve all been familiar Einstein’s famous equation, E=mc2 , since we were kids. But if you’re like me, you don’t understand the theory of relativity. You don’t need to, to write the program above. You just need to know that some variable Energy is equal to the mass times the speed of light squared. Simply put, an algorithm is a systematic solution to a problem. It can take the form of a simple equation like above, or it can take the form of several equations, or several equations and various new variables. As long as there is a systematic way to get form point A to point B you have an algorithm. You’re not always expected, as a beginning programmer, to come up with the algorithm yourself. Many times the algorithm will be given to you by the people requesting the program. But as you progress as a programmer, you will be responsible more and more for the algorithm yourself. An experienced programmer spends most of his or her time figuring out algorithms. Once you have the algorithm, the code should more or less write itself. There are two techniques figuring out algorithms. First you can write an outline, in English, describing how you want the program to work. If you can’t find the words to describe what you want your program to do, you haven’t figured out the algorithm yet. The second approach is called stepwise refinement. We’ll cover both of these approaches in later chapters. Compiling and Debugging Before we start taking our program apart, piece-by-piece, perhaps we should run it first to make sure it works. Here we encounter the first snag. The computer doesn’t understand our program, also known as the source code, any better than you do. As far as the computer is concerned our source code is just another word processing document, no different than a letter to Mom. Computers run on a series of zeros and ones called machine language. Before we can run our program we need to convert our source code into machine language. That’s what compilers do. They take higher level, C++ programming code that can be written and understood by human beings, and convert it into executable machine language. Mac, Windows and UNIX computers have different types of CPUs and therefore use different types of machine languages. So they each require their own compiler. Make sure you get a compiler that will generate machine code for your computer. You may have heard C++ being referred to as an Object Oriented Program. One of the advantages of OOPs is that the same code can be used on different computer platforms. Our program will run on Mac, Windows, and UNIX computers without any changes. It just has to be compiled three times, once on each platform. While you need a compiler to run the program you don’t need a special program to write it. You can use any word processor. You just need to be able to move the program from your word processor
  • 3. © 1998, 2010 by Lindsey Anderson. All Rights Reserved. into the compiler. You can do this by either copy and pasting or by saving your word processor file as text and importing the text file into your compiler, assuming that it can import text. You’re only going to be using a word processor to write your source code when you’re using a public domain compiler like gnu++. If your using a modern commercial compiler, then it will (or you shouldn’t buy it) have a built in text editor. The built in text editor is better than a word processor because it helps you avoid errors by automatically indenting your blocks of code and making sure every brace and parenthesis has a match. You should be aware that there may be variations from one compiler to another. The C++ language is not static. Like your word processor or your spreadsheet, there are periodic improvements. Every few years a group, the ANSI standards committee, gets together and reviews and approves changes in the C++ language. If your source code incorporates the latest and greatest features, it may not compile with an older compiler. All the concepts covered in this book are standard and have been around for a while so they should compile just fine. When we are compiling a program we are creating a separate and independent file that contains the machine code. It is a common practice to give the executable file a name similar to the program name with the extension, .exe, to identify it as the executable file. The .exe extension is helpful but not absolutely necessary. In summary, then, when we say we are running the program, we are not actually running the program (the source code) per se; we are running the executable file. Compiling is a three step process: preprocessor, object, and linking. During the preprocessor stage the compiler looks for the #include command. If it can’t find #include then it moves directly to the object stage. This #include command alerts the preprocessor that there are libraries that our program needs to reference in order to generate executable code. Our program uses two libraries, iostream.h and math.h. We will cover libraries in more detail later but here’s the quick and dirty. Why reinvent the wheel? Libraries have code that can be used by many programs. It is much easier to include the library than to rewrite the same code a million times. Furthermore the quality of the code in a library will be better than what you would write yourself because it has been optimized for speedy performance. The preprocessor stage looks for included libraries but does not incorporate their code into an executable file at this point. The preprocessor stage is just concerned with whether the compiler can find the libraries. The actually incorporating of the library code occurs in the linking stage. If the compiler can’t find the libraries you will get an error message to that effect. In the object stage the compiler generates the machine language for the executable file. Before it makes the conversion it first checks your source code to make sure there are no syntax or lexical errors. We will define syntax and lexical errors shortly. If there are errors, the compiler will give you an appropriate error message and not generate machine code. You must then debug your errors and try compiling again. Once the compiler successfully generates the object code then it incorporates the links from the libraries into the executable code. The linked files are already in machine language so we don’t have to worry about converting the links into machine language. Back in the late 1980’s, the C++ stone age, compiling and linking were distinct operations that you had to do separately. First you would use the compiler generated a separate object file. Then you would run a separate program called a linker, similar to a compiler, on the object file to incorporate the linked library files into the object code so that you could create an execution file.
  • 4. © 1998, 2010 by Lindsey Anderson. All Rights Reserved. Modern compilers combine the compiling and linking functions into the compiler. In theory the compiler still creates a separate object file but you never see it or have any control over it. The compiler automatically links the libraries to the object file and generates the executable file. The reason for this history lesson is that you could have an old C++ program that requires separate steps for compiling and linking. So much for background, now lets compile our program. When we do so, we get the following error message: our_program.cc: In function `int main(...)': our_program.cc:16: parse error before `>' What we have here is a bug in the form of a syntax error. Syntax errors are errors in grammar or punctuation. There should be a semi-colon after mass on line 16. We will spend a great deal of time discussing the grammar and punctuation of C++ as we go along. Syntax errors are not the only kind of bug we will encounter. There are also lexical, execution, and intent errors. Lexical errors occur when our program contains a word or words that is not in the C++ vocabulary. The C++ language has a series of key words, like “if”, that it automatically understands. If you misspell a keyword, or if you fail to define a variable before using it, you will get a lexical error that will produce an error message. Execution errors occur after the program has been compiled. If you ever used a computer, you’ve experienced an execution error. Everything seems to be running just fine, until suddenly the computer bombs. There is nothing a compiler can do to help you avoid execution errors. You just have to make sure you include error checking and fool proofing as you write your program. We’ll discuss how to do this in future chapters. Finally we could have an error of intent. Intent error mean that the program compiles and runs fine, but does not give the correct answer. For example, if we had POW (LIGHT-SPEED,3) instead of POW (LIGHT-SPEED,2) in our program, everything would work just fine except we would get the wrong answer. Now that we have fixed the syntax error by putting a semi-colon after float mass, lets run the program and see what we get: Please enter the mass in Kg: 15 The energy is 1.34801e+18 When we enter in a positive number for mass and: Please enter the mass in Kg: -25 Please try again and enter a positive number. when we enter in a negative. So our error checking is working fine. In the examples above the items we inputted from the keyboard are underlined. When we run the program we get the message to Please enter the mass in Kg: The computer then pauses waiting for us to input from our keyboard the amount of mass. The computer will continue to pause and pause and pause until the amount for mass is entered. So the user has to be alert. Once the mass has been imputed the computer outputs the amount of energy converted from the mass.
  • 5. © 1998, 2010 by Lindsey Anderson. All Rights Reserved. Comments Now lets take a look at the various parts or the program. The first thing we see in our program is: /* This program uses Einstein’s famous equation, E=mc2 , from his Theory of Relativity to convert a given mass (in kilograms) into energy */ This is a comment that explains what the program does. You should always start your program with a similar statement. The ideal of C++ is to write once and use many times. No one else is going to be able to use your code unless they know what it does. And if you’re like me, six months after you’ve written your code, you’ll have no idea what it does unless you used comments. It is not enough just to comment what the program does. You must also explain how it works. Weeks or months down the road you, your coworkers, or your successor may encounter a problem similar to the one solved by your program. The easiest way to solve a similar problem is to modify a program you’ve already written. But if you don’t use comments to explain your code, no one, including yourself, is going to be able to figure out your code quickly enough to make modifying worthwhile. It will be faster just to write new code. When you write a program you will test and debug before implementing. Unfortunately it may take months, even year, for some bugs to surface. So the most important reason for commenting your code is because you or someone else may have to debug it months or years after its implementation. If you are studying C++ in an academic environment, you will find that the most difficult test questions will be those where you have to debug some else’s code. Of course there are never any comments! As those precious minutes slip away, and you stare at the incomprehensible and convoluted code, you’ll wish that there were just a few comments. Don’t make yourself or anyone else suffer this agony, make sure you comment your code! Comments are for human beings; they never get compiled. When the compiler sees a comment it ignores it. There are two ways to write comments. You can enclose your comments in /* */ pairs between which you can write as much as you want or you can comment a single line with //. The // approach is limited to a single line. If the comment goes beyond a line like this: if (mass<=0) //error checking make sure the value of mass is greater than zero then your program will not compile because the compiler will think that is, greater, than, and zero are undeclared variables. There are two common errors beginning programmers make around comments. It is easy to start a long comment with /* and then forget to close with */. If you forget to close the comment then the compiler will interpret the whole program as being a comment and nothing will happen. We already covered the other common error of letting comments preceded by a // to go beyond a single line. Of course, you can work around the one line rule by using // on the second line. We did this in our program above.
  • 6. © 1998, 2010 by Lindsey Anderson. All Rights Reserved. Indents and Blocks Lets take look at our program’s structure: /* This program uses Einstein’s famous equation, E=mc2 , from his Theory of Relativity to convert a given mass (in kilograms) into energy */ #include <iostream.h> //library containing cin, cout, //<<, & >> #include <math.h> //library containing power function pow() const float LIGHT_SPEED=2.9977925e8; /* declaring constant for speed of light in meters/sec */ float main() { cout << "Please enter the mass in Kg: "; float mass; //this is line 16 cin >> mass; // user inputs value of mass in Kg if (mass<=0) //error checking make sure the value of { //mass is great than zero cout << "Please try again and enter a positive number." << endl; return 0; } float energy; energy=mass * pow (LIGHT_SPEED,2); cout << "The energy is " << energy << 'n'; } Notice that everything is aligned on the left margin until we get to the main () function. Everything within the main function is enclosed within a left brace, {, and a right brace, }. Everything between left and right braces is known as a block. Blocks are a visual clue that a group of code goes together. To even enhance this visual effect, it is good programming practice to indent the code within a block, as we did with the main() block. There is an important difference between braces and indents. Braces are required syntax while indents are not. Our program would be harder to read without indents, but it would still work. Without the braces the program would never compile. Here are some key points on brace syntax. Make use you use the curly braces {}, and not the square brackets []. Braces are always a match set. Don't forget the end brace, }.
  • 7. © 1998, 2010 by Lindsey Anderson. All Rights Reserved. We can have as many blocks are we need within a program. In our example we also have the statement: if (mass<=0) //error checking make sure the value of { //mass is great than zero cout << "Please try again and enter a positive number." << endl; return 0; } The block: { //mass is great than zero cout << "Please try again and enter a positive number." << endl; return 0; } is part of the if statement that is within the main() block. Notice that it is indented even more than the rest of the main() block. Once again this additional indenting is good programming practice but it is not necessary for the program to run. Libraries The C++ language is designed to be modular. Not all the required functionality is within the language itself. Libraries like iostream.h and the math.h are need for additional functionality or ease of use. The iostream library adds input/output capability. Without iostream we would not get the request to "Please enter the mass in Kg: " or have the opportunity to enter a value into the variable mass. We need the math.h library to use the pow function. However, in our example, the math.h library is providing ease of use rather than required functionality because we could have just as easily written our equation as energy=mass * LIGHT_SPEED * LIGHT_SPEED. Of course, if we had a program that raised the power of LIGHT_SPEED to 1,000, we would justify the use of the math library on grounds of functionality and not ease of use. No responsible programmer is going to put * LIGHT_SPEED a thousand times. How would anyone check it for errors? Instead a responsible programmer would use the pow function, pow (LIGHT_SPEED,1000), because it provides necessary functionality. Its hard to put your finger on exactly where, but at some point, easy of use gives way to functionality. The pow function is just one of the many functions built into the math.h library. Others in include absolute value, floor, ceiling, and the like. While the grammar is different, these built in functions are similar in concept to the built in functions in Microsoft Excel and other spreadsheets. Later in this book we will describe what some of these other functions do and how to use them. The iostream.h and the math.h libraries are just two of many. Other libraries include ctype.h, time.h, and iomanip.h. While these particular libraries are so common that you can expect them to be available with your C++ program, don’t assume that every library you may find in a reference book will be available. To find out if an interesting library is available, you either have to check the documentation of your software or just include the library in a program and see if the compiler finds it.
  • 8. © 1998, 2010 by Lindsey Anderson. All Rights Reserved. During the precompile stage the compiler needs to be able to find the libraries. Generally, when your C++ program is installed, it places the common libraries in the same folder or directory as the compiler itself. Consequently the compiler has no trouble finding the libraries. If you have C++ on your personal computer, be careful not to throw out or move the libraries, or your compiler will not find them. Thus far we have been talking about the built in libraries. You can also create your own libraries. We’ve mentioned the goal of write once use many times. If you have written code that you want to use again in another program you would create a library to hold that code and then include the library within the other program. For example, if our program had some code that used the library goodies.h, we would have had the statement #include <goodies.h> along with #include <iostream.h> and #include <math.h>. You will learn how to create your own libraries at the end of the book when we cover Classes. Here is some of the syntax of Libraries. They are always called in the beginning of the program with the keyword #include. The name of the library is always within angle brackets, <>. Have you noticed that all our libraries have the suffix .h? The .h refers to header. The header file just has the declarations of the various functions. The details reside in another file. When we get to the chapter on Classes, this will make more sense. Earlier we discussed ANSI standards. One of the improvements of the latest ANSI meeting was to eliminate the .h in the most common library headers. Your compiler may or may not have incorporated this change. Try #include<iostream> without the .h in a program. If it works, fine, if not put back the .h. We will continue to use the .h throughout this book. Variables You have been using variables since high school algebra, if not before. We can rewrite Einstein’s formula in the more familiar algebraic form: y=(8.98676e16)x Here y is the energy, x is the mass and the constant, LIGHT_SPEED squrared, is replaced with its actual value. In our program we have the variables energy and mass but we are also treating the constant, LIGHT_SPEED, as a variable. We don’t have to treat constants like variables. We could have used: energy=mass * (8.98676e16) but we would have lost the instant recognition of Einstein equation. LIGHT_SPEED squared is more obvious. The first step in using a variable is to declare it by identifing the variable type as well as its name. When we declared LIGHT_SPEED, const float LIGHT_SPEED=2.9977925e8; we said was of type float. We also said that mass and energy were of type float. Float is one of the two most common variable types but there are many more. We will cover other variable types in future chapters. When we declared LIGHT_SPEED we immediately initialized it. Initialization is the process of giving variables a value. There are three ways to initialize a variable. First we can make the initial value part of the declaration as we did with LIGHT_SPEED. Secondly we can initialize the variable from the
  • 9. © 1998, 2010 by Lindsey Anderson. All Rights Reserved. keyboard as we did with mass. Finally we can initialize a variable with a formula like we did with energy. If you use this last approach make sure you initialize all the other variables in the formula first. If mass and LIGHT_SPEED hadn’t already been initialized, we would have gotten an error message during compiling. Variables are the backbone of each and every program. They are the most important objects of object oriented programming. Without variables we wouldn’t have computers. We are going to spend the next chapter exclusively on variables. We will also discuss other types of variables in future chapters. Input/Output This is the process by which we get information in and out of the program. We already discussed the need for the iostream.h library. This library adds the functionality of cout, cin, <<, & >>. Output is a function of cout (pronounced see-out). When we want the computer to output a message we use a statement like: cout << "Please enter the mass in Kg: "; Whenever we want the program to print something on our computer monitor we start the statement with cout and follow it with the output operator, <<. The statement itself must be within straight quotes ("…") not curly quotes (“…”). VERY IMPORTANT: If your are writing your program on a modern word processor like Microsoft Word, you need to either turn off the smart quote feature or use the copy and paste to replace the curly quotes with straight quotes. You will get an error message when you compile using curly quotes. The statement must be limited to one line and it must conclude with a semi-colon. The way around the single line rule is to use multiple output operators. Here’s an example: cout << "This program uses Einstein’s famous equation," << "E=mc2 , from his Theory of Relativity to " << "convert a given mass (in kilograms) into" << " energy"; Notice that the semi-colon does not appear until the very end. However each line must end with a straight quote, and, after the first line, each line must start with the output operator, <<. We only need to use cout once. It is good programming practice to align all the output operators one on top of the other. Also notice either at the end of the line or at the beginning of the next line there is a space before or after the straight quote. Without that space the lines will run together like so: This program uses Einstein’s famous equation,E=mc2 , from his Theory of Relativity toconvert a given mass (in kilograms) intoenergy Finally, as in the case above, what actually outputs on the screen may not have the same line breaks as it did when you wrote the cout statement in your program. Use cin (pronounced see-in) for input along with the input operator, >>. You will use cin to input the values of variables directly into the program. In our example we used cin to input the value of mass. As long as we keep inputting numbers, one after another, they all will be part of the value of the variable. The way we tell the computer we are done inputting the value of the variable is to hit enter, return, or space on our keyboard.
  • 10. © 1998, 2010 by Lindsey Anderson. All Rights Reserved. Once you’ve made a commitment, via your program, to enter a value into a variable, you must do so. The program will hang until you enter your value and will continue to hang until you give it the signal that you’re done with the entry. When you give the signal that you are done with the data entry, the computer will automatically move to the next line on the screen. But it will not do so for screen output unless the line is full. To move screen output to the next line use the command, endl. Its easy to get the << and >> operators mixed up. Here’s an easy mnemonic devise. If the arrows are pointing into the page, >>, they are the input operator. If the arrows are pointing away, out of the page they are the output operator. main() Every C++ program has one and only one main function. That’s where the meat is. A main function always has the parentheses, (), following main, main(), and a starting brace and an ending brace. It its good programming practice to indent all the contents of a main function to make it easy to tell where the main function starts and where it ends. Everything outside the main function is support material. In our program the libraries and the declaration of the LIGHT_SPEED constant are all supporting the main function. As you become more comfortable with C++ programming, you will start writing your own functions. These too must be declared outside of the main function. Notice that the main function was declared to be of the type float, float main(). You want to declare the main function to be the same type as the variable it returns. Since our program returns the float, energy, we declare our main function to be float. We will discuss types more in the chapter on variables. Sometimes your main function may return several variables of different types. If one of those variables is an integer, then declare int main(). Otherwise just choose one of the variable types and declare your main function accordingly. Even though you may return more than one variable type within a main function, a main function can be of only one type. Sometimes a main function does not return a variable at all. In that case declare the main function as void, void main(). Some programmers will declare all main functions as void and the program will work even if it is returning integer and/or other variables. However this is not considered good programming practice. Decision Making In our program we do not want to return a value for energy, if a negative number were entered into mass. To avoid this we used an if statement to insure that the mass is positive. The if statement enables us to make a decision. The program does one thing if the test is true and nothing if the test is false. In our program the if statement tests to see if mass is negative or equal to zero. If the mass is not positive then the program tells us to enter in a positive number and stops. If mass is indeed positive, our program continues with the rest of the code. Here’s a tip to save you hours of hair pulling agony. The proper syntax of an if statement is if (test goes here). Notice that if is with a small i not a capital I. Every beginning programmer makes the mistake of using If instead of if. All forms of decision making, not just the if statement, have a test. The test must be Boolean, either true or false. In our program the test is mass<=0. The program inserts the value of mass into the test
  • 11. © 1998, 2010 by Lindsey Anderson. All Rights Reserved. and makes a determination if it is true or not. Clearly -25 is less than or equal to zero, so when -25 was entered into mass our if statement was true and the program halted. Because computers are based on a binary series of ones and zeros, it is a convention to define true as 1 and false as 0. However the more rigorous definition is that 0 is false and all other numbers are true. Consequently, while the statement, if (5), has no meaningful test, it will always be true. Lets take another look at our if statement: if (mass<=0) //error checking make sure the value of { //mass is great than zero cout << "Please try again and enter a positive number." << endl; return 0; } Notice that the test is always in parenthesis and that there is no semi-colon after the last parenthesis. If there is more than one line of code to be executed if the test is true, it is common to move the statement to the next line and enclose it in blocks like as done above. Here the braces are required because the things to do, if true, take up several lines of code. If the true response was just one line we don’t really need the braces or even a separate line. For instance this perfectly acceptable and even preferred: if (test) do this single line of code; Notice that there is still no semi-colon after the last parenthesis of the test but that there is one at the end of the line of code. Our if statement is just one of many ways, including nested if statements, of making a decision. We will spend considerable time on decision making later in this book. Error Checking: Garbage in, Garbage out In our problem we used the if statement for error checking. We wanted to avoid negative mass because there is no such thing as negative energy (ignoring anti-matter). The if statement is not the only form of error checking. If we included the assert.h library, we could have used the assert(mass>0) function. If the test is false, then assert automatically halts the program and returns the computer to the control of the operating system. However, assert is not as useful as the if statement for error checking because assert just quits without telling us why. Our if statement tells us why the program quit. We will cover other methods of checking errors as we go along. You must realize that it is your responsibility to idiot proof your program. You have to expect that users, either on purpose or by mistake, will try to enter data that will cause errors. You must do your best to anticipate such errors and write code that will preserve the operation of your program even when the user makes a mistake. In our program we were only half successful in anticipating user errors. While we guarded against the user entering in a negative number, we did not anticipate the user entering text rather than a number. If the user typed the word, five, instead of the number 5, our program would have crashed. We will cover how to handle this kind of error later in the book. return 0 When we had negative mass, we used the statement, return 0;, to quit our program. You can use return 0 to quit any program; so you must be judicious in its use. Only use return 0 when you want to
  • 12. © 1998, 2010 by Lindsey Anderson. All Rights Reserved. terminate a program midstream. Don’t use it to end a program; the ending brace, }, of the main() function will do that. The statement, return 0, is not the only case in which you will use the keyword, return. You will use return later, when you start creating your own functions and Boolean expressions. Keywords There are certain words in C++, known as keywords, that have special meaning to C++. Here is a list of those words: asm namespace auto new bool operator break private case protected catch public char register class reinterpret_cast const return const_cast short continue signed default sizeof delete static do static_cast double struct dynamic_cast switch else template enum this explicit throw extern true false try float typedef for typeid friend typename goto union if unsigned inline using int virtual long void mutable volatile while Do not use these words as variables or for anything else other than their predefined meaning. We have already touched upon the meanings of if and return. We will cover many, but not all, of the other keywords as we go along. In addition to keywords there are other words that are what we will call special. Notice that our list of keywords does not include cout, cin, or endl. These words became special when you use the iostream.h library. Once you have included the iostream.h library you can not use these words for variables; but you can use them as variables if you have not included the iostream library.
  • 13. © 1998, 2010 by Lindsey Anderson. All Rights Reserved. Keywords and special words are all case sensitive. We already pointed out that If is not the same thing as if. Since all the keywords and special words are all in lower case, use only lower case when using them. Arithmetic Operators Einstein’s equation, E=mc2 , will not work directly in C++. The C++ language does not fully follow the rules of algebra that you learned in high school. The compiler would perceive mc2 as the undeclared variable, mc2. You can not assume arithmetic operators, like multiplication, by putting two or more variables next to each other, as in mc2 . Operators must be explicit. In this case the explicit operator is the same * you use on a pocket calculator. Neither does C++ recognize algebraic conventions for exponents. That is why the mc2 of Einstein’s equation becomes the undeclared variable mc2. You must use the pow function or spell out the multiplication (c * c). In Einstein’s equation the = sign means equal, but in C++ the = sign is the assignment operator. The equals sign is ==. In our example this distinction is so subtle that it is practically lost. In our program we are not saying that Energy is equal to mass * pow (LIGHT_SPEED,2); we are saying that the variable, Energy, is being assigned (or gets) the value of mass * pow (LIGHT_SPEED,2). Why bother with this distinction when the outcome is the same? Because the outcome is not always the same. Here are two examples where the outcomes are very different. There are times when you may want to keep track of how many times a certain event occurs, so you declare a variable, counter. Every time the event occurs you want to advance the counter by 1. You would do it like so: counter=counter+1 Now clearly counter cannot be equal to itself plus 1; yet this is a valid C++ expression. What it means is take the old value of counter and add 1 to it and then replace the old value of the counter with the new. For example if our counter had a value of 5 and if another instance of the event we are counting occurred, we would assign counter the value of the old counter, 5, plus 1, for a new value of 6. Here’s another example. Suppose you were doing something with weights that required special handling when the weight equaled 100. If you used the expression: if (weight=100) you would always perform the special handling because the expression, (weight=100), would, regardless of the original value of weight, set weight equal to 100. The proper expression is: if (weight==100) Here special handling would be required only if the value of weight were equal to 100. There are many other instances where C++ does not adhere to the conventions of algebra. We will cover those instances in the chapter on operators. Good Programming Practice We have made reference several times to good programming practice and we will continue to do so throughout this book. Good programming practice is nothing more than good programming conventions or habits.
  • 14. © 1998, 2010 by Lindsey Anderson. All Rights Reserved. Good programming practice is not the same thing as syntax. Ignore the rules of syntax and your program will fail to run. Ignore good programming practices and your program will run but it may be harder to read and understand. Remember the whole point of using an object oriented programming language like C++ is to make it easier to you and others to reuse code whenever possible. Failure to use good programming practice undermines OOPs by making it harder to recycle code.