Category : C Source Code
Archive   : CPTUTOR1.ZIP
Filename : CHAP01.TXT

 
Output of file : CHAP01.TXT contained in archive : CPTUTOR1.ZIP



Chapter 1
SIMPLE THINGS

As we begin the study of C++ and object oriented programming, a few
comments are in order to help you get started. Since the field of
object oriented programming is probably new to you, you will find
that there is a significant amount of new terminology for you to
grasp. This is true of any new endeavor and you should be warned
not to be intimidated by all of the new concepts. We will add a
few new topics in each chapter and you will slowly grasp the entire
language.

Chapters one through four of this tutorial will concentrate on the
non object oriented programming additions to C++. We will not
begin the discussion of any object oriented programming techniques
until chapter five.


EVEN COMMENTS ARE IMPROVED IN C++
_________________________________________________________________

Examine the file named CONCOM.CPP for an example ==============
of several new things in C++. We will take the CONCOM.CPP
new constructs one at a time beginning with the ==============
comments.

A comment begins with the double slash "//", starts anywhere on a
line and runs to the end of that line where it is automatically
terminated. The old method of comment definition used with ANSI-
C can also be used with C++ as illustrated in lines 11 through 14,
among other places in this program. The new method is the
preferred method of comment definition because it is impossible to
inadvertently comment out several lines of code. This can be done
by forgetting to include the end of comment notation when using the
older C method of comment notation. Good programming practice
would be to use the new method for all comments and reserve the old
method for use in commenting out a section of code during debugging
since the two methods can be nested.

It would be well to caution you at his point however, that you
should not use comments when the same sense of program definition
can be obtained by using meaningful names for variables, constants,
and functions. The careful selection of variable and function
names can make nearly any code self documenting and you should
strive to achieve this in your code.

THE KEYWORDS const AND volatile
_________________________________________________________________

There are two new keywords used in lines 9 through 11 which were
not part of the original K&R definition of C, but are part of the
ANSI-C standard. The keyword const is used to define a constant.
In line 9 the constant is of type int, it is named START, and is

Page 1-1

Chapter 1 - Simple Things

initialized to the value 3. The compiler will not allow you to
accidentally or purposefully change the value of START because it
has been declared a constant. If you had another variable named
STARTS, the system would not allow you to slightly misspell STARTS
as START and accidentally change it. The compiler would give you
an error message so you could fix the error. Since it is not
permissible to change the value of a constant, it is imperative
that you initialize it when it is declared so it will have a useful
value. The compiler does not require you to initialize it however,
and will not issue an error message if you do not.

You will note that the keyword const is also used in the function
header in line 21 to indicate that the formal parameter named
data_value is a constant throughout the function. Any attempt to
assign a new value to this variable will result in a compile error.
This is a small thing you can add to your programs to improve the
compilers ability to detect errors for you.

The keyword volatile is also part of the ANSI-C standard but was
not included in the original K&R definition of C. Even though the
value of a volatile variable can be changed by you, the programmer,
there may be another mechanism by which the value could be changed,
such as by an interrupt timer causing the value to be incremented.
The compiler needs to know that this value may be changed by some
external force when it optimizes the code. A study of code
optimization methods is very interesting, but beyond the scope of
this tutorial. Note that a constant can also be volatile, which
means that you cannot change it, but the system can through some
hardware function.

Ignore the output statement given in line 23 for a few minutes.
We will study it in some detail later in this chapter. If you are
experienced in K&R style programming, you may find line 5 and 21
a little strange. This illustrates prototyping and the modern
method of function definition as defined by the ANSI-C standard.
We will discuss this in great detail in chapter 4 of this tutorial.
Prototyping is optional in C but absolutely required in C++. For
that reason, chapter 4 of this tutorial is devoted entirely to this
topic.

It would be advantageous for you to compile and execute this
program with your C++ compiler to see if you get the same result
as given in the comments at the end of the listing. One of the
primary purposes of compiling it is to prove that your compiler is
loaded and executing properly.



THE SCOPE OPERATOR
_________________________________________________________________

The example program named SCOPEOP.CPP illustrates another construct
that is new to C++. There is no corresponding construct in either
K&R or ANSI-C. This allows access to the global variable named

Page 1-2

Chapter 1 - Simple Things

index even though there is a local variable of ===============
the same name within the main function. The use SCOPEOP.CPP
of the double colon in front of the variable ===============
name, in lines 11, 13, and 16, instructs the
system that we are interested in using the
global variable named index, defined in line 4, rather than the
local variable defined in line 8.

The use of this technique allows access to the global variable for
any use. It could be used in calculations, as a function
parameter, or for any other purpose. It is not really good
programming practice to abuse this construct, because it could make
the code difficult to read. It would be best to use a different
variable name instead of reusing this name, but the construct is
available to you if you find that you need it sometime.

The scope operator allows access to global variables even though
hidden by a local variable. Be sure to compile and execute this
program before proceeding on to the next example program where we
will discuss the cout operator in lines 10, 11, 15, and 16.



THE iostream LIBRARY
_________________________________________________________________

Examine the example program named MESSAGE.CPP ===============
for our first hint of object oriented MESSAGE.CPP

programming, even though it is a very simple ===============
one. In this program, we define a few variables
and assign values to them for use in the output
statements illustrated in lines 17 through 20, and in lines 23
through 26. The new operator cout is the output function to the
standard device, the monitor, but works a little differently from
our old familiar printf() function, because we do not have to tell
the system what type we are outputting.

C++, like the C language itself, has no input or output operations
as part of the language itself, but allows the implementor to add
input and output functions in a very elegant manner. This has been
done for us in the stream library.

The operator <<, sometimes called the "put to" operator, tells the
system to output the variable or constant following it, but lets
the system decide how to output the data. In line 17, we first
tell the system to output the string, which it does by copying
characters to the monitor, then we tell it to output the value of
index. Notice however, that we fail to tell it what the type is
or how to output the value. Since we don't tell the system what
the type is, it is up to the system to determine what the type is
and to output the value accordingly. After the system finds the
correct type, we also leave it up to the system to use the built
in default as to how many characters should be used for this
output. In this case, we find that the system uses exactly as many

Page 1-3

Chapter 1 - Simple Things

as needed to output the data, with no leading or trailing blanks,
which is fine for this output. Finally, the newline character is
output, and the line of code is terminated with a semicolon.

When we called the cout output function in line 17, we actually
called two different functions because we used it to output a
string and a variable of type int. This is the first hint at
object oriented programming because we simply broadcast a message
to the system to print out a value, and let the system find an
appropriate function to do so. We are not required to tell the
system exactly how to output the data, we only tell it to output
it. This is a very weak example of object oriented programming,
and we will get into it in much more depth later.

In line 18, we tell the system to output a different string,
followed by a floating point number, and another string of one
character, the newline character. In this case, we told it to
output a floating point number without telling it that it was a
floating point number, once again letting the system choose the
appropriate output means based on its type. We did lose a bit of
control in the transaction, however, because we had no control over
how many significant digits to print before or after the decimal
point. We chose to let the system decide how to format the output
data.


The variable named letter is of type char, and is assigned the
value of the uppercase X in line 14, then printed as a letter in
line 19. You have complete flexibility in the use of the cout and
the printf() statements and they can be mixed in any way you
desire. Both statements result in output to the monitor.


MORE ABOUT THE stream LIBRARY
_________________________________________________________________

The stream library was defined for use with C++ in order to add to
the execution efficiency of the language. The printf() function
was developed early in the life of the C language and is meant to
be all things to all programmers. As a result, it became a huge
function with lots of extra baggage that is only used by a few
programmers. By defining the small special purpose stream library,
the designer of C++ allows the programmer to use somewhat limited
formatting capabilities, but which are still adequate for most
programming jobs. If more elaborate formatting capabilities are
required, the complete printf() library is available from C, and
the two types of outputs can be freely mixed.

Lines 23 through 26 illustrate some of the additional features of
the stream library which can be used to output data in a very
flexible yet controlled format. The value of index is printed out
in decimal, octal, and hexadecimal format in lines 23 through 25.
When one of the special stream operators, dec, oct, or hex, is
output, all successive output will be in that number base. Looking

Page 1-4

Chapter 1 - Simple Things

ahead to line 32, we find the value of index printed in hex format
due to the selection of the hexadecimal base in line 25. If none
of these are output, the system defaults to decimal format.


THE cin OPERATOR
_________________________________________________________________

In addition to the cout operator, there is a cin operator which is
used to read data from the standard input device, usually the
keyboard. The cin operator uses the >> operator, usually called
the "get from" operator and it has most of the flexibility of the
cout operator. A brief example of the use of the cin operator is
given in lines 28 through 30. The special stream operators, dec,
oct, and hex, also select the number base for the cin stream
separately from the cout stream. If none is specified, the input
stream also defaults to decimal.

In addition to the cout operator and the cin operator there is one
more standard operator, the cerr, which is used to output to the
error handling device. This device cannot be redirected to a file
like the output to the cout can be. The three operators, cout,
cin, and cerr, correspond roughly to the stdout, the stdin, and the
stderr stream pointers of the programming language C. Their use
will be illustrated throughout the remainder of this tutorial.

The stream library also has file I/O capability, but it is beyond
the scope of this tutorial. The standard file I/O library is
available with ANSI-C and is as easy to use as the stream library
and very portable. For more information on the stream file I/O
library, see Bjarne Stroustrup's book which is listed in the
introduction to this tutorial.

Be sure to compile and execute this program before going on to the
next one. Remember that the system will ask you to enter an
integer value which will be echoed back to the monitor, but changed
to the hexadecimal base.



FILE STREAM OPERATIONS
_________________________________________________________________

Examine the example program named FSTREAM.CPP ===============
for examples of the use of streams with files. FSTREAM.CPP
In this program a file is opened for reading, ===============
another for writing, and a third stream is
opened to the printer to illustrate the semantics of stream
operations on a file. The only difference between the streams in
the last program and the streams in this program is the fact that
in the last program, the streams were already opened for us by the
system. You will note that the stream named printer is used in the
same way we used the cout operator in the last program. Finally,

Page 1-5

Chapter 1 - Simple Things

because we wish to exercise good programming practice, we close
all of the files we have opened prior to ending the program.

Be sure to compile and execute this program. When you execute it,
it will request a file to be copied. You can enter the name of any
ASCII file that resides in the current directory.



VARIABLE DEFINITIONS
_________________________________________________________________

Examine the file named VARDEF.CPP for a few more ==============
additions to the C++ language which aid in VARDEF.CPP
writing a clear and easy to understand program. ==============
In C++, as in ANSI-C, global and static
variables are automatically initialized to zero
when they are declared. This is true in both C++ and ANSI-C. The
variables named index in line 4, and goofy in line 26 are therefore
automatically initialized to zero. Of course, you can still
initialize either to some other value if you so desire. Global
variables are sometimes called external since they are external to
any functions.

Automatic variables, those declared inside of any function, are not
automatically initialized but will contain the value that happens
to be in the location where they are defined, which must be
considered a garbage value. The variable named stuff in line 8,
therefore does not contain a valid value, but some garbage value
which should not be used for any meaningful purpose. In line 11,
it is assigned a value based on the initialized value of index and
it is then displayed on the monitor for your examination.



THE REFERENCE VARIABLE
_________________________________________________________________

Notice the ampersand in line 9. This defines another_stuff as a
reference variable which is a new addition to C++. The reference
variable should not be used very often, if at all, in this context.
In order to be complete however, we will discuss its operation.
The reference variable is not quite the same as any other variable
because it operates sort of like a pointer. Following its
initialization, the reference variable becomes a synonym for the
variable stuff, and changing the value of stuff will change the
value of another_stuff because they are both actually referring to
the same variable. The synonym can be used to access the value of
the variable for any legal purpose in the language. It should be
pointed out that a reference variable must be initialized when it
is declared or the compiler will respond with an error. Following
initialization, the reference variable cannot be changed to refer
to a different variable.


Page 1-6

Chapter 1 - Simple Things

Even though the use of the reference variable in this way can lead
to very confusing code, it has another use where it can make the
code very clear and easy to understand. We will study this use in
chapter 4 of this tutorial.


DEFINITIONS ARE EXECUTABLE STATEMENTS
_________________________________________________________________

Coming from your background of C, you will find the statement in
line 16 very strange, but this is legal in C++. Anyplace it is
legal to put an executable statement, it is also legal to declare
a new variable because a data declaration is defined as an
executable statement in C++. In this case, we define the new
variable named more_stuff and initialize it to the value of 13.
It has a scope from the point where it was defined to the end of
the block in which it is defined, so it is valid throughout the
remainder of the main program. The variable named goofy is
declared even later in line 26.

It is very significant that the variable is declared near its point
of usage. This makes it easier to see just what the variable is
used for since it has a much more restricted scope of validity.
When you are debugging a program, it is convenient if the variable
declaration is located in close proximity to where you are
debugging the code.



WHAT ABOUT definition AND declaration?
_________________________________________________________________

The words definition and declaration refer to two different things
in C++, and in ANSI-C also for that matter. They really are
different and have different characteristics so we should spend a
little time defining exactly what the words mean in C++. A
declaration provides information to the compiler about the
characteristics of something such as a type or a function but it
doesn't actually define any code to be used in the executable
program, and you are permitted to make as many declarations of the
same entity as you desire. A definition, on the other hand,
actually defines something that will exist in the executable
program, either some useful variables, or some executable code, and
you are required to have one and only one definition of each entity
in the program. In short, a declaration introduces a name into the
program and a definition introduces some code.

If we declare a struct, we are only declaring a pattern to tell the
compiler how to store data later when we define one or more
variables of that type. But when we define some variables of that
type, we are actually declaring their names for use by the
compiler, and defining a storage location to store the values of
the variables. Therefore, when we define a variable, we are
actually declaring it and defining it at the same time.

Page 1-7

Chapter 1 - Simple Things


We will refer to these definitions many times throughout the course
of this tutorial so if this is not clear now, it will clear up
later.


A BETTER for LOOP
_________________________________________________________________

Take careful notice of the for loop defined in line 20. This loop
is a little clearer than the for loop that is available in ANSI-C,
because the loop index is defined in the for loop itself. The
scope of this loop index is from its declaration to the end of the
enclosing block. In this case its scope extends to line 29 since
the closing brace in line 29 corresponds to the most recent opening
brace prior to the declaration of the variable. Since the variable
is still available, it can be used for another loop index or for
any other purpose which an integer type variable can legally be
used for. The variable named count2 is declared and initialized
during each pass through the loop because it is declared within the
block controlled by the for loop. Its scope is only the extent of
the loop so that it is automatically deallocated each time the loop
is completed. It is therefore declared, initialized, used and
deallocated five times, once for each pass through the loop.

You will notice that the variable count2 is assigned a numerical
value in line 22 but when it is printed out, a character value is
actually output. This is because C++ (version 2.0 and later) is
careful to use the correct type.

Finally, as mentioned earlier, the static variable named goofy is
declared and automatically initialized to zero in line 26. Its
scope is from the point of its declaration to the end of the block
in which it is declared, line 29.

Be sure to compile and execute this program.



OPERATOR PRECEDENCE
_________________________________________________________________

Operator precedence is identical to that defined for ANSI-C so no
attempt will be made here to define it. There is a small
difference when some operators are overloaded which we will learn
to do later in this tutorial. Some of the operators act slightly
different when overloaded than the way they operate with elements
of the predefined language.

Do not worry about the previous paragraph, it will make sense later
in this tutorial after we have studied a few more topics.




Page 1-8

Chapter 1 - Simple Things

PROGRAMMING EXERCISES
_________________________________________________________________


1. Write a program that displays your name and date of birth on
the monitor three times using the cout function. Define any
variables you use as near as possible to their point of usage.

2. Write a program with a few const values and volatile variables
and attempt to change the value of the constants to see what
kind of error message your compiler will give you.












































Page 1-9



  3 Responses to “Category : C Source Code
Archive   : CPTUTOR1.ZIP
Filename : CHAP01.TXT

  1. Very nice! Thank you for this wonderful archive. I wonder why I found it only now. Long live the BBS file archives!

  2. This is so awesome! 😀 I’d be cool if you could download an entire archive of this at once, though.

  3. But one thing that puzzles me is the “mtswslnkmcjklsdlsbdmMICROSOFT” string. There is an article about it here. It is definitely worth a read: http://www.os2museum.com/wp/mtswslnk/