Day 1
Week1
Getting Your Feet Wet
by Kent Reisdorph
Congratulations—you’ve chosen one of today’s hottest new programming
tools! Before you can jump into using all of what C++Builder has to offer,
though, you’ll need to learn a little about C++ first. In this chapter you will find
n A quick tour of C++Builder
n Information about how to write a Win32 console-mode application
n An introduction to the C++ language
n Facts about C++ variables and data types
n Information about functions in C++ (including the main() function)
n A discussion of arrays
4 Day 1
What Is C++Builder?
By now you know that C++Builder is Borland’s hot new rapid application development
(RAD) product for writing C++ applications. With C++Builder you can write C++ Windows
programs more quickly and more easily than was ever possible before. You can create Win32
console applications or Win32 GUI (graphical user interface) programs. When creating
Win32 GUI applications with C++Builder, you have all the power of C++ wrapped up in a
RAD environment. What this means is that you can create the user interface to a program
(the user interface means the menus, dialog boxes, main window, and so on) using drag-anddrop
techniques for true rapid application development. You can also drop OCX controls
on forms to create specialized programs such as Web browsers in a matter of minutes.
C++Builder gives you all of this, but you don’t sacrifice program execution speed because you
still have the power that the C++ language offers you.
I can hear you saying, “This is going to be so cool!” And guess what? You’re right! But before
you go slobbering all over yourself with anticipation, I also need to point out that the C++
language is not an easy one to master. I don’t want you to think that you can buy a program
like C++Builder and be a master Windows programmer overnight. It takes a great deal of
work to be a good Windows programmer. C++Builder does a great job of hiding some of the
low-level details that make up the guts of a Windows program, but it cannot write programs
for you. In the end, you must still be a programmer, and that means you have to learn
programming. That can be a long, uphill journey some days. The good news is that
C++Builder can make your trek fairly painless and even fun. Yes, you can work and have fun
doing it!
So roll up your sleeves and get your hiking shoes on. C++Builder is cool, so have fun.
A Quick Look at the C++Builder IDE
This section contains a quick look at the C++Builder IDE. We’ll give the IDE a once-over
here, and we’ll examine it in more detail on Day 6, “The C++Builder IDE Explored: Projects
and Forms.” Because you are tackling Windows programming, I’ll assume you are advanced
enough to have figured out how to start C++Builder. When you first start the program, you
are presented with both a blank form and the IDE, as shown in Figure 1.1.
The C++Builder IDE (which stands for integrated development environment) is divided into
three parts. The top window might be considered the main window. It contains the speedbar
on the left and the Component Palette on the right. The speedbar gives you one-click access
to tasks like opening, saving, and compiling projects. The Component Palette contains a
wide array of components that you can drop onto your forms. (Components are things like
text labels, edit controls, list boxes, buttons, and the like.) For convenience, the components
Getting Your Feet Wet 5
1
A component is a self-contained piece of binary software that performs some specific
predefined task, such as a text label, an edit control, or a list box.
Below the speedbar and Component Palette and glued to the left side of the screen is the
Object Inspector. It is through the Object Inspector that you modify a component’s
properties and events. You will use the Object Inspector constantly as you work with
C++Builder. The Object Inspector has one or two tabs, depending on the component
currently selected. It always has a Properties tab. A component’s properties control how the
component operates. For example, changing the Color property of a component will change
the background color of that component. The list of available properties varies from
component to component, although components usually have several common elements
(Width and Height properties, for instance).
NEW TERM
Figure 1.1.
The C++Builder
IDE and the initial
blank form.
are divided into groups. Did you notice the tabs along the top of the Component Palette? Go
ahead and click on the tabs to explore the different components available to you. To place
a component on your form, you simply click the component’s button in the Component
Palette and then click on your form where you want the component to appear. Don’t worry
about the fact that you don’t yet know how to use components. We’ll get to that in due time.
When you are done exploring, click on the tab labeled Standard, because you’ll need it in a
moment.
6 Day 1
A property determines the operation of a component.
Usually the Object Inspector has an Events tab in addition to the Properties tab. Events occur
as the user interacts with a component. For example, when a component is clicked, an event
fires and tells Windows that the component was clicked. You can write code that responds
to those events, performing specific actions when an event occurs. As with properties, the
events that you can respond to vary from component to component.
An event is a method that is invoked in a component as a result of that component’s
interaction with the user.
To the right of the Object Inspector is the C++Builder workspace. The workspace initially
displays the Form Editor. It should come as no surprise that the Form Editor allows you to
create forms. In C++Builder a form represents a window in your program. The form might
be the program’s main window, a dialog box, or any other type of window. You use the Form
Editor to place, move, and size components as part of the form creation process. Hiding
behind the Form Editor is the Code Editor. The Code Editor is where you type code when
writing your programs. The Object Inspector, Form Editor, Code Editor, and Component
Palette work interactively as you build applications.
Now that you’ve had a look at what makes up the C++Builder IDE, let’s actually do
something.
Hello World
It’s tradition. Almost all programming books start you off by having you create a program
that displays Hello World on the screen. I’m tempted to do something else, but tradition is
a force to be reckoned with, so Hello World it is. You’ve got some work ahead of you in the
next few chapters, so I thought I’d give you a taste of C++Builder’s goodies before putting
you to work on learning the seemingly less-glamorous basics of C++. You’ll have a little fun
before you have to go on the chain gang. C++Builder (and its cousin,
you the quickest route to Hello World of any Windows programming environment to date.
Right now you should have C++Builder running, and you should be looking at a blank form.
By default, the form is named Form1. (The form name is significant in C++Builder, but I’ll
address that a little later.) To the left of the form, the Object Inspector shows the properties
for the form. Click on the title bar of the Object Inspector. The Caption property is
highlighted, and the cursor is sitting there waiting for you to do something. (If the Caption
property is not in view, you might have to scroll the Object Inspector window to locate it.
Properties are listed in alphabetical order.) Type Hello World! to change the form’s caption.
NEW TERM
NEW TERM
Getting Your Feet Wet 7
1
As you modify properties, C++Builder will immediately display the
results of the property change when appropriate. As you type the new
caption, notice that the window caption of the form is changing to
reflect the text you are typing.
Now click the Run button on the speedbar (the one with the green arrow). (You could also
press F9 or choose Run | Run from the main menu.) C++Builder begins to build the
program. The compiler status dialog box, shown in Figure 1.2, is displayed, and you can
watch as C++Builder whips through the files necessary to build your program. After a brief
wait, the compiler status box disappears, the form is displayed, and the caption shows Hello
World!. In this case, the running program looks almost identical to the blank form. You may
scarcely have noticed when the program was displayed because it is displayed in the exact
location of the form in the Form Editor. (There is a difference, though, because the Form
Editor displays an alignment grid and the running program does not.) Congratulations—
you’ve just written your first C++ Windows program with C++Builder. Wow, that was easy!
“But what is it?” you ask. It’s not a lot, I agree, but it is a true Windows program. It can be
moved by dragging the title bar, it can be sized, it can be minimized, it can be maximized,
and it can be closed by clicking the Close button.
NOTE
Figure 1.2.
The compiler status
dialog box.
Okay, so maybe displaying Hello World! just in the caption was cheating a little. Let’s spruce
it up a bit. If you still have the Hello World program running, close it by clicking the Close
button in the upper-right corner of the window. The Form Editor is displayed again, and you
are ready to modify the form (and, as a result, the program).
To make the program more viable, we’re going to add text to the center of the window itself.
To do this, we’ll add a text label to the form. First, click on the Standard tab of the
Component Palette. The third component button on the palette has an A on it. If you put
your mouse cursor over that button, the tool tip will display Label. Click the label button and
then click anywhere on the form. A label component is placed on the form. Now turn your
attention to the Object Inspector. It now displays the properties for Label1 (remember that
before it was showing the properties for Form1). Again the Caption property is highlighted.
8 Day 1
Click on the title bar of the Object Inspector or on the Caption property and type Hello
World!. Now the label on the form shows Hello World!. As long as we’re at it, let’s change
the size of the label’s text as well. Double-click on the Font property. The property will expand
to show the additional font attributes below it. Locate the Size property under Font and
change the font size to 24 (it is currently set to 8). As soon as you press the Enter key or click
on the form, the label instantly changes to the new size.
Because the label is probably not centered on the form, you may want to move it. To move
a component, simply click on it and drag it to the position you want it to occupy. Once you
have the label where you want it, you’re ready to recompile and run the program. Click the
Run button again. C++Builder compiles the program again and, after a moment (shorter this
time), the program runs. Now you see Hello World! displayed in the center of the form as
well as in the caption. Figure 1.3 shows the Hello World program running.
Figure 1.3.
The Hello World
program running.
With this little taste of C++Builder, you can see that writing C++ Windows programs with
C++Builder is going to be a great deal more interesting than it was in the good ol’ days. To
prepare for what you are going to do next, you need to close the current project in the
C++Builder IDE. Choose File | Close All from the main menu. Click No when prompted
to save changes to Project1, or save the project as HelloWorld if you are fond of your new
creation.
Hello World, Part II—A Win32 Console
Application
In the next couple chapters you are going to learn the basics of the C++ language. Along the
way you will write some simple test programs. These test programs will work best as console
applications. For all intents and purposes, these programs look like DOS programs when they
run. There are some major differences between a Win32 console app and a DOS program,
Getting Your Feet Wet 9
1
but you need not be concerned about that right now. So, without further ado, let’s create
Hello World as a Win32 console program with C++Builder.
A Win32 console application is a 32-bit program that runs in a DOS box under
Windows 95 or Windows NT.
From the main menu, choose File | New. C++Builder displays the Object Repository.
Curiously enough, the Object Repository’s title bar says New Items, but don’t be thrown by
that. The Object Repository contains predefined projects, forms, dialog boxes, and other
objects you can add to your applications or use to begin a new project. I will discuss the Object
Repository in detail on Day 9, “Creating Applications in C++Builder.” For now, click on the
New tab in the Object Repository and double-click Console App to start a new console
application project. C++Builder creates the project and displays the Code Editor so that you
can enter code for the program. Figure 1.4 shows the Code Editor as it appears when starting
a new console-mode application.
NEW TERM
Figure 1.4.
The C++Builder
Code Editor window.
You will notice a couple of differences between the C++Builder IDE now and how it looked
earlier when we created a GUI application. First, there is no Form Editor. That’s because a
console application can’t display forms (well, that’s not completely true, but it’s accurate
enough for this discussion). Also notice that the Object Inspector is blank. You can only place
components on a form, so the Object Inspector is useless in a console application.
When writing console applications, you can close the Object Inspector
to make more room for the Code Editor window. Close the Object
Inspector by clicking the Close button on the Object Inspector’s title
bar. To bring back the Object Inspector, press F11 or choose
View | Object Inspector from the main menu.
TIP
10 Day 1
When you examine the Code Editor, you should see the following text displayed in the editor
window:
//--------------------------------
#include
#include
#include
#pragma hdrstop
//--------------------------------
int main(int argc, char **argv)
{
return 0;
}
//--------------------------------
This is a do-nothing C++ program, but a valid C++ program nonetheless. We’ll
modify the code in just a moment to make this program actually do something, but
first I want you to notice the lines that begin with //. These are comment lines that, in this
program, serve no purpose other than to divide the program’s code visually. (You will
normally use comment lines to document your code.) C++Builder adds these comment lines
automatically when a new console application is first created. (In future code listings I will
eliminate the comment lines to save space.) Notice also that the single statement in this code
ends in a semicolon. (I know it doesn’t make sense right now, but there is only one actual
executable statement in this program.) The semicolon is used at the end of each statement
in a C++ program.
Very early in the process of learning the C and C++ languages, the budding programmer
must learn the difference between an expression and a statement. The “official” definition
of a statement is “an expression that is followed by a semicolon.” The semicolon closes an
expression and makes it a kind of single-line block of code. I’ll get into the code block soon,
but for now you should realize that an expression is a unit of code that evaluates to some
quantity. A statement is an expression that is closed. For example, consider the following
statement:
c = a + b;
In this example, the portion to the right of the equal sign, a + b, is an expression. The entire
line is a statement. I know this may be a bit confusing at the moment, but it should become
clearer as we go along. I’ll try to be very careful when I use these two terms. For now, though,
just remember that a statement is followed by a semicolon and is a closed expression.
Also notice the opening and closing braces in the program. In C++, a block of code begins
with the opening brace ({) and ends with the closing brace (}). The braces are used to delineate
the beginning and end of code blocks associated with loops, functions, if statements, and in
other cases as well. In this program there is only one set of braces because it is a simple
program.
ANALYSIS
Getting Your Feet Wet 11
1
In order to display Hello World! on the screen, we need to make use of a C++ class called
iostream, so a quick tutorial on that class is needed. (You don’t know about classes yet, but
don’t worry about that right now.) The iostream class uses streams to perform basic input and
output, such as printing text on the screen or getting input from the user. The cout stream
is used to send data to the standard output stream. In a console application, the standard
output stream means the console, or the screen. The cin stream is used to get data from the
console, such as user input. iostream implements two special operators to place information
on a stream or to extract information from a stream. The insertion operator (<<) is used to insert
data into an output stream, and the extraction operator (>>) is used to extract data from an
input stream. To output information to the console, you would use
cout << “Do something!”;
This tells the program to insert the text Do something! onto the standard output stream.
When this line in the program executes, the text will be displayed on the screen.
cout is for use in console-mode applications only. A Windows GUI
application does not have a standard output stream (everything in a
GUI app is graphics based), so the output from cout goes nowhere in a
Windows GUI program. Standard Windows programs use DrawText()
or TextOut() to display text on the screen. C++Builder programs can
also use DrawText() and TextOut(), either using the Windows API or
via the TCanvas class.
Before you can use cout, you need to tell the compiler where to find the description (called
the declaration) of the iostream class. The declaration for iostream is located in a file called
IOSTREAM.H. This file is called a header file.
A header file (or header for short) contains the class declaration of one or more classes.
To tell the compiler to look in IOSTREAM.H for the class definition of iostream, use the
#include directive as follows:
#include
A declaration is a statement of intention or a foreshadowing of an event. It precedes
a definition of that event. For example, a voter declares himself to be a Democrat or
Republican. He then defines himself to be a member of that party by voting in that party’s
primary election. In C and C++, the distinction between these two separate states is very
important.
NEW TERM
NEW TERM
NOTE
12 Day 1
Now the compiler will be able to find the iostream class and will understand what to do when
it encounters the cout statement.
If you forget to include the header file for a class or a function your
program references, you will get a compiler error. The compiler error
will say something to the effect of Undefined symbol ‘cout’. If you see
this error message, you should immediately check to be sure that you
have included all of the headers your program needs. To find out what
header file a class or function’s declaration is in, click on the function
or class name and press the F1 key. Windows help will run, and the
help topic for the item under the cursor will be displayed. Toward the
top of the help topic you will see a reference to the header file in which
the function or class is declared.
There’s one more thing I’ll mention before we write the console version of Hello World. The
iostream class contains special manipulators that can be used to control how streams are
handled. The only one we are concerned with right now is the endl (end line) manipulator,
which is used to insert a new line in the output stream. We’ll use endl to insert a new line after
we output text to the screen.
Now that you have some understanding of the iostream class, we can proceed to write Hello
World as a console application. Edit the program until it looks like Listing 1.1. Each of the
lines in the listing has a number that I’ve put there for identification. Be sure to skip that
number and the space after it when you type in the lines.
Listing 1.1. HELLO.CPP.
1: #include
2: #include
3: #include
4: #include
5: #pragma hdrstop
6:
7: int main(int argc, char **argv)
8: {
9: cout << “Hello World!” <<>
10: return 0;
11: }
TIP
Getting Your Feet Wet 13
1
In C++, whitespace is ignored. For the most part, it doesn’t matter
where you put spaces or new lines. Obviously you cannot insert spaces
in the middle of keywords or variable names, but other than that just
about anything goes. For example, the following bits of code are
equivalent:
int main(int argc, char **argv)
{
cout << “Hello World!”;
return 0;
}
is the same as
int main(int argc,char** argv){cout<<“Hello World!”;return 0;}
Obviously, the first form is more readable and is much preferred.
While coding styles vary, if you emulate the coding conventions you
see in this book, you should be okay when it comes to programming in
the real world.
Now click the Run button on the speedbar. The program compiles and runs. When
the program runs you will see a DOS box pop up and the words Hello World!…whoops!
What happened? You probably saw the application for a split second and then watched as it
disappeared. The reason for this is that at the end of the main() function the program
terminates and the console window immediately closes. To remedy this we need to add a
couple of lines to our program to prevent the console window from closing until we’re done
with it. The standard C library includes a function called getch() that is used to get a
keystroke from the keyboard. We’ll use that as a means of preventing the console window
from closing. Again, edit the program in the editor window until it looks like Listing 1.2. You
don’t need to add the comment lines if you don’t want to. Remember to skip the line
numbers.
Listing 1.2. HELLO.CPP (revised).
1: #include
2: #include
3: #include
4: #include
5: #include
6: #pragma hdrstop
7:
8: int main(int argc, char **argv)
NOTE
ANALYSIS
continues
14 Day 1
9: {
10: cout << “Hello World!” <<>
11: // add the following two lines
12: cout <<>
13: getch();
14: return 0;
15: }
This time the application runs, Hello World! is displayed, and the console window
stays visible. To end the program and close the console window, you can press any
key on the keyboard.
You can also find the programs listed in the text at http://www.mcp.com/sams/codecenter.html.
The examples need to be installed on your hard drive before they can be compiled. While it’s
good practice early on to enter short programs by hand, you may want to load the longer
sample programs from your hard drive in order to avoid inevitable typing errors and the
compiler errors that are sure to follow.
That’s all there is to it. Hello World, Part II isn’t too exciting, but you’ll make good use of
console-mode applications as you explore the C++ language in the following pages. That’s
why it is necessary for you to understand how to create and run a console-mode application.
Now let’s move on to the basics of the C++ language.
C++ Language Overview
C++ is a powerful language. It allows you to do things that are not possible in other languages.
As is true in most of life, that kind of power does not come without responsibility. It could
be said that C++ gives you just enough rope to hang yourself—and while starting out learning
C++, you often will hang yourself. This usually comes in the form of memory overruns and
access violations that will cause crashes in your programs.
I will do my best to describe C++ in the short space allotted. Entire books have been written
on the C++ language (and big ones at that!), so do not expect that I can cover it all in a couple
chapters. I strongly suggest that, after you read this book and experiment with C++Builder
for a period of time, you buy a book that explains C++ in greater detail.
C++ allows you to take advantage of object-oriented programming (OOP) to its fullest. OOP
is not just a buzzword. It has real benefits because it allows you to create objects that can be
used in your current program and reused in future programs.
Listing 1.2. continued
ANALYSIS
Getting Your Feet Wet 15
1
An object, like components described earlier, is a piece of binary software that
performs a specific programming task. (Components are objects, but not all objects
are components. I’ll get into that later.)
An object reveals to the user (the programmer using the object) only as much of itself as
needed in order to simplify its use. All internal mechanisms that the user doesn’t need to know
about are hidden from sight. All of this is rolled up in the concept of object-oriented
programming. OOP allows you to take a modular approach to programming, thus keeping
you from constantly re-inventing the wheel. C++Builder programs are OOP-oriented due to
C++Builder’s heavy use of components. Once a component is created (either one of your own
or one of the built-in C++Builder components), it can be reused in any C++Builder program.
A component can also be extended by inheritance to create a new component with additional
features. Best of all, components hide their internal details and let the programmer
concentrate on getting the most out of the component. Objects and C++ classes are discussed
in detail on Day 4, “Totally Immersed: C++ Classes and Object-Oriented Programming.”
Humble Beginnings
In the beginning there was C…as far as C++ is concerned, anyway. C++ is built on the C
programming language. It has been described as “C with classes.” This foundation in C is still
very prevalent in C++ programs written today. It’s not as if C++ were written to replace C,
but rather to augment it. The rest of this chapter and much of the next chapter focus primarily
on the part of the C++ language that has its roots in C. Actually, we will be dealing with the
C language here and moving to C++ later, on Day 2, “Wading In Deeper.” You don’t have
to be concerned with which of the information presented is from C and which is from C++
because it’s all rolled up into the language we call C++.
It would be nice if presenting the C++ language could be handled sequentially. That’s not
the case, though, because all of the features we will be discussing are intertwined. Presenting
the C++ language sequentially is not possible, so I’ll take the individual puzzle pieces one at
a time and start fitting them together. Toward the end of Day 3, “Up to Your Neck in C++,”
you’ll have a fairly complete picture of the C++ language. Don’t be concerned if you do not
instantly grasp every concept presented. Some of what is required to fully understand C++
can only come with real-world experience.
Variables
Well, we have to start somewhere, so let’s take a look at variables. A variable is essentially a
name assigned to a memory location. Once you have declared a variable, you can then use
it to manipulate data in memory. That probably doesn’t make much sense to you, so let me
NEW TERM
16 Day 1
give you a few examples. The following code snippet uses two variables. At the end of each
line of code is a comment that describes what is happening when that line executes:
int x; // variable declared as an integer variable
x = 100; // ‘x’ now contains the value 100
x += 50; // ‘x’ now contains the value 150
int y = 150; // ‘y’ declared and initialized to 150
x += y; // ‘x’ now contains the value 300
x++; // ‘x’ now contains the value 301
A variable is a location set aside in computer memory to contain some value.
Notice that the value of x changes as the variable is manipulated. I’ll discuss the C++ operators
used to manipulate variables a little later.
Variables that are declared but are not initialized will contain random
values. Because the memory to which the variable points has not been
initialized, there is no telling what that memory location contains. For
instance, look at the following code:
int x;
int y;
x = y + 10; // oops!
In this example the variable x could contain any value because y was
not initialized prior to use.
The exception to this rule is that global variables and variables declared
with the static modifier are initialized to 0. All other variables contain
random data until initialized or assigned a value.
Variable names can mix upper- and lowercase letters and can include numbers and the
underscore (_ ), but they cannot contain spaces or other special characters. The variable name
must start with a character or the underscore. Generally speaking, it’s not a good idea to begin
a variable name with an underscore because compilers often start special variable and function
names with the underscore. The maximum allowed length of a variable name will vary from
compiler to compiler. If you keep your variable names to 31 characters or less, you’ll be safe.
In reality, anything more than about 20 characters is too long to be useful anyway.
C++ Data Types
In C++ a data type defines the way the compiler stores information in memory.
NEW TERM
WARNING
NEW TERM
Getting Your Feet Wet 17
1
In some programming languages you can get by with assigning any type of value to a variable.
For example, look at the following examples of BASIC code:
x = -1;
x = 1000;
x = 3.14
x = 457000;
In BASIC the interpreter takes care of allocating enough storage to fit any size or type of
number. In C++, however, you must declare a variable’s type before you can use the variable:
int x1 = -1;
int x = 1000;
float y = 3.14;
long z = 457000;
This allows the compiler to do type-checking and to make sure that things are kept straight
when the program runs. Improper use of a data type will result in a compiler error or warning
that can be analyzed and corrected so that you can head off a problem before it starts. Some
data types can have both signed and unsigned versions. A signed data type can contain both
negative and positive numbers, whereas an unsigned data type can contain only positive
numbers. Table 1.1 shows the basic data types in C++, the amount of memory they require,
and the range of values possible for that data type.
Table 1.1. Data types used in C++ (32-bit programs).
Data Type Size in Bytes Possible
char 1 -128 to 126
unsigned char 1 0 to 255
short 2 -32,768 to 32,767
unsigned short 2 0 to 65,535
long 4 -2,147,483,648 to
2,147,483,648
unsigned long 4 0 to 4,294,967,295
int 4 Same as long
unsigned int 4 Same as unsigned long
float 4 1.2E-38 to 3.4E381
double 8 2.2E-308 to 1.8E3082
bool 1 true or false
18 Day 1
In C++Builder (as well as in Borland C++ 5.0), bool is a true data type.
Some C++ compilers have a BOOL keyword, but bool is not a data type
in those compilers. In those cases BOOL is a typedef that makes the BOOL
equivalent to an int. A typedef in effect sets up an alias so that the
compiler can equate one symbol with another. A typedef looks like this:
typedef int BOOL;
This tells the compiler, “BOOL is another word for int.”
Only the double and float data types use floating-point numbers
(numbers with decimal places). The other data types deal only with
integer values. Although it’s legal to assign a value containing a decimal
fraction to an integer data type, the fractional amount will be discarded
and only the whole-number portion will be assigned to the integer
variable. For example,
int x = 3.75;
will result in x containing a value of 3. Note that the resulting integer
value is not rounded to the nearest whole number; rather, the decimal
fraction is discarded altogether. By the way, you’d be surprised how few
times you need floating-point numbers in most Windows programs.
C++ will perform conversion between different data types when possible. Take the following
code snippet for an example:
short result;
long num1 = 200;
long num2 = 200;
result = num1 * num2;
In this case I am trying to assign the result of multiplying two long integers to a short integer.
Even though this formula mixes two data types, C++ is able to perform a conversion. Would
you like to take a guess at the result of this calculation? You may be surprised to find out that
the result is -25,536. This is due to wrapping. If you look at Table 1.1, you’ll see that a short
can have a maximum value of 32,767. What happens if you take a short with a value of 32,767
and add 1 to it? You will end up with a value of -32,768. This is essentially the same as the
odometer on a car turning over from 99,999 to 00,000 when you drive that last mile. To
illustrate, type in and run the program contained in Listing 1.3.
NOTE
NOTE
Getting Your Feet Wet 19
1
Listing 1.3. WRAPME.CPP.
1: #include
2: #include
3: #pragma hdrstop
4:
5: int main(int argc, char **argv)
6: {
7: short x = 32767;
8: cout << “x = “ <<>
9: x++;
10: cout << “x = “ <<>
11: getch();
12: return 0;
13: }
The output will be
x = 32767
x = -32768
You won’t go too far wrong if you use the int data type as your data type of choice. You are
unlikely to run into the problem of wrapping because the int data type gives you a range of
-2 billion to +2 billion, plus change. Your programs will be slightly larger, however, because
you will be using more memory than required in many situations.
Okay, where was I? Oh, yes, I was talking about automatic type conversion. In some cases,
C++ cannot perform a conversion. If that is the case, you will get one of several possible
compiler errors that essentially say Cannot convert from X to Y. You may also get a compiler
warning that says, Conversion may lose significant digits.
Learn to treat compiler warnings as errors because the compiler is
trying to tell you that something is not quite right. Ultimately, you
should strive for warning-free compiles. In some cases a warning cannot
be avoided, but be sure to examine all warnings closely. Do your best to
understand the reason for the warning and correct it if possible.
C++ Operators
Operators are used to manipulate data. Operators perform calculations, check for equality,
make assignments, manipulate variables, and other more esoteric duties most programmers
TIP
20 Day 1
never get into. There are a lot of operators in C++. Rather than present them all here, I will
list only those most commonly used. Table 1.2 contains a list of those operators.
Table 1.2. Commonly used C++ operators.
Operator Description Example
Mathematical Operators
+ Addition x = y + z;
– Subtraction x = y - z;
* Multiplication x = y * z;
/ Division x = y / z;
Assignment Operators
= Assignment x = 10;
+= Assign and sum x += 10; (same as x = x + 10;)
-= Assign and subtract x -= 10;
*= Assign and multiply x *= 10;
\= Assign and divide x \= 10;
&= Assign bitwise AND x &= 0x02;
|= Assign bitwise OR x |= 0x02;
Logical Operators
&& Logical AND if (x && 0xFF) {...}
|| Logical OR if (x || 0xFF) {...}
Equality Operators
== Equal to if (x == 10) {...}
!= Not equal to if (x != 10) {...}
< Less than if (x <>
> Greater than if (x > 10) {...}
<= Less than or equal to if (x <= 10) {...}
>= Greater than or equal to if (x >= 10) {...}
Getting Your Feet Wet 21
1
Unary Operators
* Indirection operator int x = *y;
& Address of operator int* x = &y;
~ Bitwise NOT x &= ~0x02;
! Logical NOT if (!valid) {...}
++ Increment operator x++; (same as x = x + 1;)
-- Decrement operator x--;
Class and Structure Operators
:: Scope resolution MyClass::SomeFunction();
-> Indirect membership myClass->SomeFunction();
. Direct membership myClass.SomeFunction();
As you can see, the list of operators is a bit overwhelming, so don’t worry about trying to
memorize each one. As you work with C++ you will gradually learn how to use all of the
operators.
It should be noted that in some cases an operator can be used either pre-increment (++x) or
post-increment (x++). A pre-increment operator tells the compiler, “Increment the variable’s
value and then use the variable.” A post-increment operator tells the compiler, “Use the
variable first and then increment its value.” For example, this code
int x = 10;
cout << “x = “ <<>
cout << “x = “ <<>
cout << “x = “ << ++x <<>
cout << “x = “ x <<>
will result in the following output:
x = 10
x = 11
x = 12
x = 12
A lot of this won’t make sense until you’ve worked with C++ for a while, but be patient and
it will eventually come to you. As Pontius said to Augustus, “Relax, Augie.
in a day, ya know.”
Operator Description Example
22 Day 1
In C++, operators can be overloaded. This is a technique by which a
programmer can take one of the standard operators and make it perform
in a specific manner for a specific class. For example, you could overload
the ++ operator for one of your classes and have it increment the value of
a variable by 10, rather than by 1. Operator overloading is an advanced
C++ technique and won’t be covered in any detail in this book.
You will notice that some of the operators use the same symbol. The meaning of the symbol
is different depending on the context. For instance, the asterisk (*) can be used to perform
multiplication, declare a pointer, or dereference a pointer. This can be confusing at first, and
to be honest, it can be confusing at times no matter how long you’ve been programming in
C++. Just keep plugging away and eventually it will start to sink in.
You will see many examples of these operators as you go through this book. Rather than trying
to memorize the function of each operator, try instead to learn through careful study of the
example programs and code snippets.
Functions in C++
Functions are sections of code separate from the main program. These code sections are called
(executed) when needed to perform specific actions in a program. For example, you might
have a function that takes two values, performs a complex mathematical calculation on those
two values, and returns the result. Or you might need a function that takes a string, parses
it, and returns a portion of the parsed string.
Functions are sections of code, separate from the main program, that perform a
single, well-defined service.
Functions are an important part of any programming language, and C++ is no exception. The
simplest type of function takes no parameters and returns void (meaning it returns nothing
at all). Other functions may take one or more parameters, and may return a value. Rules for
naming functions are the same as those discussed earlier for variables. Figure 1.5 shows the
anatomy of a function.
A parameter is a value passed to a function that is used to alter its operation or indicate
the extent of its operation.
Before a function can be used, it must have first been declared. The function declaration, or
prototype, tells the compiler how many parameters the function takes, the data type of each
parameter, and the data type of the return value for the function. Listing 1.4 illustrates this
concept.
NOTE
NEW TERM
NEW TERM
Getting Your Feet Wet 23
1
A prototype is a declaration of a function’s appearance or a foreshadowing of its
definition.
NEW TERM
Figure 1.5.
Anatomy of a
function.
Return Type Function Name Parameter List
int SomeFunction (int x, int y)
{
int z = (x * y);
return z;
}
Function Body
Return
Statement
Listing 1.4. MULTIPLY.CPP.
1: #include
2: #include
3: #pragma hdrstop
4:
5: int multiply(int, int);
6: void showResult(int);
7:
8: int main(int argc, char **argv)
9: {
10: int x, y, result;
11: cout <<>
12: cin >> x;
13: cout << “Enter the second value: “;
14: cin >> y;
15: result = multiply(x, y);
16: showResult(result);
17: cout <<>
18: getch();
19: return 0;
20: }
21:
22: int multiply(int x, int y)
23: {
24: return x * y;
25: }
26:
27: void showResult(int res)
28: {
29: cout << “The result is: “ <<>
30: }
This program asks for two numbers from the user (using the standard input stream, cin) in
lines 11 through 14, calls the multiply() function to multiply the two numbers together (line
15), and then calls the showResult() function to display the result (line 16). Notice the
24 Day 1
function prototypes for the multiply() and showResult() functions on lines 5 and 6, just
above the main program. The prototypes list only the return type, the function name, and
the data type of the function’s parameters. That is the minimum requirement for a function
declaration.
If desired, the function prototype may contain variable names that can be used to document
what the function does. For example, the function declaration for the multiply() function
could have been written like this:
int multiply(int firstNumber, int secondNumber);
In this case it’s pretty obvious what the multiply() function does, but it can’t hurt to
document your code both through comments and through the code itself.
Look again at Listing 1.4. Notice that the function definition for the multiply() function
(lines 22 through 25) is outside of the block of code defining the main function (lines 8
through 20). The function definition contains the actual body of the function. In this case
the body of the function is minimal because the function simply multiplies the two function
parameters together and returns the result.
The multiply() function in Listing 1.4 could be called one of several ways. You can pass
variables, literal values, or even the results of other function calls:
result = multiply(2, 5); // passing literal values
result = multiply(x, y); // passing variables
showResult(multiply(x,y)); // return value used as a
// parameter for another function
multiply(x, y); // return value ignored
Notice in this example that the return value is not used. In this case it doesn’t make much
sense to call the multiply() function and ignore the return value, but ignoring the return
value is something that is done frequently in C++ programming. There are many functions
that perform a specific action and then return a value indicating the status of the function call.
In some cases the return value is not relevant to your program, so you can just ignore it. If
you don’t do anything with the return value, it is simply discarded and no harm is done. For
example, we have been ignoring the return value of the getch() function (which returns the
ASCII value of the key that was pressed) in our sample programs.
Functions can (and frequently do) call other functions. Functions can even call themselves.
This is called recursion, and is one way to get into trouble in C++ programming. Recursion
is best left alone until you’ve put in some time with the C++ language.
Recursion is the process by which a function calls itself.
The material on functions presented in this section deals with standalone functions in a C
or C++ program (they are standalone in that they are not members of a class). Standalone
NEW TERM
Getting Your Feet Wet 25
1
functions can be used in C++ exactly as they can be used in C. However, C++ takes functions
a bit further. I’ll leave that discussion for now and pick it up again later when we look deeper
into C++.
HOUSE RULES FOR FUNCTIONS
n A function can take any number of parameters or no parameters at all.
n A function can be written to return a value, but it is not mandatory that a function
return a value.
n If a function has a return type of void, it cannot return a value. If you attempt to
return a value from a function with a return type of void, a compiler error will be
issued. A function that returns void need not contain a return statement at all, but
it may if desired. Either way is acceptable. If no return statement is provided, the
function returns automatically when it gets to the end of the function block (the
closing brace).
n If the function prototype indicates that the function returns a value, the function
body should contain a return statement that returns a value. If the function does
not return a value, a compiler warning is issued.
n Functions can take any number of parameters but can return only one value.
n Variables can be passed to functions by value, by pointer, or by reference. (I’ll
discuss this a little later.)
The function statement, in declaration (prototype) format:
ret_type function_name(argtype_1 arg_1, argtype_2 arg_2, ..., argtype_n arg_n);
The function declaration identifies a function that will be included in the code. It shows the
return data type (ret_type) of the function and the name of the function (function_name),
and identifies the order (arg_1, arg_2, …, arg_n) and types (argtype_1, argtype_2, …,
argtype_n) of data arguments the function will expect.
The function statement, in definition format:
ret_type function_name(argtype_1 arg_1, argtype_2 arg_2, ..., argtype_n arg_n) {
statements;
}
The function definition identifies the code block (statements) that makes up the function
and shows the return data type (ret_type) of the function. function_name identifies the
function. The parameters supplied to the function (arg_1, arg_2, …, arg_n) and their types
(argtype_1, argtype_2, …, argtype_n) are included.
SYNTAX
t
s
26 Day 1
The main() Function
A C++ program must have a main() function. This function serves as the entry point into the
program. You have seen this in each of the sample programs you’ve seen thus far. Not all C++
programs have a traditional main() function, however. Windows programs written in C and
C++ have an entry-point function called WinMain() rather than the traditional main()
function.
A C++Builder GUI application has a WinMain(), but it is hidden from
you. C++Builder frees you from having to worry about the low-level
details of a Windows program and allows you to concentrate on
creating the user interface and the remainder of the program.
main() is a function like any other function. That is, it has the same basic anatomy. You
already saw that for a 32-bit console application C++Builder creates a default main() function
with the following prototype:
int main(int argc, char** argv);
This form of main() takes two parameters and returns an integer value. As you learned earlier,
you pass values to a function when you call the function. In the case of main(), though, you
never call the function directly—it’s automatically executed when the program runs. So how
does the main() function get its parameters? The answer: From the command line. Let me
illustrate.
Let’s assume that you have a Win32 console application that you execute from a DOS prompt
with the following command line:
grep WM_KILLFOCUS -d -i
In this case you are starting a program called grep with command-line arguments of
WM_KILLFOCUS, -d, and -i. Given that example, let me show you how that translates to argc
and argv inside the main() function. First of all, the integer variable argc will contain the
number of parameters passed in the command line. This will always be at least 1 because the
program name counts as a parameter. The variable argv is an array of pointers to strings. This
array will contain each string passed in the command line. For this code example, the
following are true:
argv contains 4
argc[0] contains c:\bc5\bin\grep.com
argc[1] contains WM_KILLFOCUS
argc[2] contains -d
argc[3] contains -i
NOTE
Getting Your Feet Wet 27
1
Let’s prove that this works with a little sample program. Create a new console application in
C++Builder and enter the program shown in Listing 1.5.
Listing 1.5. ARGSTEST.CPP.
1: #include
2: #include
3: #pragma hdrstop
4:
5: int main(int argc, char **argv)
6: {
7: cout << “argc = “ <<>
8: for (int i=0;i
9: cout << “Parameter “ <<>
10: getch();
11: return 0;
12: }
Save the project as ARGSTESTCPP. Rather than clicking the Run button, choose Project | Build
All from the main menu. This will build the project but won’t execute the program. When
the project has finished building, choose Run | Parameters from the main menu. Type the
following in the Run parameters dialog box:
one two three “four five” six
Now click the Run button, and the program will run using the command-line parameters
you specified. An alternative is to run the program from an MS-DOS prompt by using the
following command line:
argstest one two three “four five” six
When the program runs it will display the number of arguments passed and then list each of
the arguments. The output should match that of Figure 1.6. Run the program several times,
providing different command-line arguments each time, and observe the output.
Figure 1.6.
Sample output from
ARGSTEST.EXE.
28 Day 1
In most programs the value returned from main() is irrelevant because the return value is not
typically used. In fact, you don’t need your main() function to return a value at all. There is
more than one form of main(). The following all represent valid declarations:
main();
int main();
int main(int argc, char** argv);
void main(); // same as the first form above
void main(int argc, char** argv);
Believe it or not, there are even more possibilities than those listed here. If you are not going
to be using the command-line arguments and are not returning a value from main(), you can
use the first form of main() listed here. This form returns a void and takes no parameters
(signified by the empty parentheses). In other words, the most basic form of the main()
function takes no parameters and returns no value.
Arrays
You can place any of the intrinsic C++ data types into an array. An array is simply a collection
of values. For example, let’s say you wanted to keep an array of ints that held five integer
values. You would declare the array as follows:
int myArray[5];
In this case the compiler allocates memory for the array as illustrated in Figure 1.7. Because
each int requires 4 bytes of storage, the entire array will take up 20 bytes in memory.
Figure 1.7.
Memory allocation
for an array of
five ints.
myArray[0] myArray[1] myArray[2] myArray[3] myArray[4]
baseAddr baseAddr+4 baseAddr+8 baseAddr+12 baseAddr+16
Now that you have the array declared, you can fill it with values using the subscript operator
([]) as follows:
myArray[0] = -200;
myArray[1] = -100;
myArray[2] = 0;
myArray[3] = 100;
myArray[4] = 200;
Later in your program you can access the individual elements of the array again using the
subscript operator:
int result = myArray[3] + myArray[4]; // result will be 300
Getting Your Feet Wet 29
1
There is a shortcut method to declaring and filling an array all at one time. It looks like this:
int myArray[5] = { -200, -100, 0, 100, 200 };
To take this one step further, if you know exactly how many elements your array will have,
and if you fill the array when you declare it, you can even leave out the array size when you
declare the array. In that case you would use the following:
int myArray[] = { -200, -100, 0, 100, 200 };
This works because the compiler can figure out from the list of values being assigned how
many elements are in the array and how much memory to allocate for the array.
Arrays can be multidimensional. To create a two-dimensional array of integers, you would
use code like this:
int mdArray[3][5];
This allocates storage for 15 ints (a total of 60 bytes, if you’re keeping score). You access
elements of the array like you do a simple array, with the obvious difference that you must
supply two subscript operators:
int x = mdArray[1][1] + mdArray[2][1];
Figure 1.8 illustrates how a two-dimensional array might look in memory.
Figure 1.8.
A two-dimensional
array in memory.
myArray[][0] myArray[][1] myArray[][2] myArray[][3] myArray[][4]
baseAddr baseAddr+4 baseAddr+8 baseAddr+12 baseAddr+16
baseAddr+20 baseAddr+24 baseAddr+28 baseAddr+32 baseAddr+36
baseAddr+40 baseAddr+44 baseAddr+48 baseAddr+52 baseAddr+56
Array[0][]
Array[1][]
Array[2][]
You must be careful not to overwrite the end of an array. One powerful
feature of C++ is direct access to memory. Because of this feature, C++
will not prevent you from writing to a particular memory location even
if that location is memory your program isn’t supposed to have access
to. The following code is legal, but will result in a crash in your
program (or in Windows):
int array[5];
array[5] = 10;
This is a common error to make because you might think the last
element of this array is 5 when it is really 4. If you overwrite the end of
an array, you have no idea what memory you are overwriting. The
WARNING
30 Day 1
NEW TERM
results will be unpredictable at best. At worst, you will crash your
program and maybe even crash Windows, too. This type of problem
can be difficult to diagnose because often the affected memory is not
accessed until much later, and the crash occurs at that time (leaving you
wondering what happened). Be careful when writing to an array.
HOUSE RULES FOR ARRAYS
n Arrays are 0 based. The first element in the array is 0, the second element is 1, the
third element is 2, and so on.
n Array sizes must be compile-time constants. The compiler must know at compile
time how much space to allocate for the array. You cannot use a variable to assign
an array size, so the following is not legal and will result in a compiler error:
int x = 10;
int myArray[x]; // compiler error here
n Be careful not to overwrite the end of an array.
n Allocate large arrays from the heap rather than from the stack. (You’ll learn more
about this later.)
Character Arrays
Odd as it may seem, there is no support in C++ for a string variable (a variable that holds text).
Instead, strings in C++ programs are represented by arrays of the char data type. For instance,
you could assign a string to a char array as follows:
char text[] = “This is a string.”;
This allocates 18 bytes of storage in memory and stores the string in that memory location.
Depending on how quick you are, you may have noticed that there are only 17 characters in
this string. The reason that 18 bytes are allocated is that at the end of each string is a
terminating null, and C++ accounts for the terminating null when allocating storage.
The terminating null is a special character that is represented with /0, which equates
to a numerical 0.
Getting Your Feet Wet 31
1
When the program encounters a 0 in the character array, it interprets that location as the end
of the string. To see how this is done, enter and run Listing 1.6 as a console application.
Listing 1.6. NULLTEST.CPP.
1: #include
2: #include
3: #pragma hdrstop
4:
5: int main(int argc, char **argv)
6: {
7: char str[] = “This is a string.”;
8: cout <<>
9: str[7] = ‘\0’;
10: cout <<>
11: getch();
12: return 0;
13: }
Figure 1.9 shows the output from the program in Listing 1.6.
Initially, the character array contains the characters, This is a string. followed by
the terminating null. That string is sent to the screen via cout. The next line assigns
the seventh element of the array to \0, which is, of course, the terminating null. The string
is again sent to the screen, but this time only This is is displayed. The reason for this is that
as far as the computer is concerned, the string ends at element 7 in the array. The rest of the
characters are still in storage but can’t be displayed because of the terminating null. Figure
1.10 illustrates how the character array looks before and after the line that changes element
7 to the terminating null.
ANALYSIS
Figure 1.9.
The output from
NULLTEST.CPP.
32 Day 1
I could have simply assigned a 0 in place of ‘\0’ in Listing 1.6. Either is acceptable because
a numerical 0 and the char data type version, ‘\0’, are equivalent.
There is a difference between single and double quotes in a C++
program. When assigning the terminal null (or any other character
value) to an element of an array, you must use single quotes. The single
quotes effectively turn the character within the quotes into an integer
value (the ASCII value of the character) that is then stored in the
memory location. When assigning strings to character arrays, you must
use double quotes. If you get it wrong in either case, the compiler will
let you know by issuing a compiler error.
String-Manipulation Functions
If you are coming from a programming language that has a string data type, all of this might
seem like a pain. The truth is, it takes very little time to get used to. You’re not completely
on your own, by the way. In order to aid in string operations, the standard C library has several
functions for string manipulation. Table 1.3 lists the most frequently used stringmanipulation
functions and a description of each. For a complete description of each of these
functions and examples of their use, see the C++Builder online help.
Table 1.3. String-manipulation functions.
Function Description
strcat() Concatenates (adds) a string to the end of the target string.
strcmp() Compares two strings for equality.
strcmpi() Compares two strings for equality without case sensitivity.
strcpy() Copies the contents of one string to the target string.
strstr() Scans a string for the first occurrence of a substring.
Figure 1.10.
The contents of a
character array.
T h i s i s a s t r i n g . \0
T h i s i s \0 a s t r i n g . \0
Before
After
NOTE
Getting Your Feet Wet 33
1
strlen() Returns the length of the string.
strupr() Converts all characters in a string to uppercase.
sprintf() Builds a string based on a variable number of parameters.
The string operations discussed here are how strings are handled in C.
Most C++ compilers provide a cstring class that simplifies the difficulties
inherent in the C way of handling strings. (C++Builder’s Visual
Component Library contains a class called Strings that handles string
operations. Check the C++Builder online help for more information on
Strings.) Although the C way of handling strings is a little quirky, it is
by no means obsolete. C++ programmers use C-style string operations
on a daily basis as well as string classes such as cstring.
I won’t go into examples of all of the string-manipulation functions listed in the table, but
I’ll touch on a couple of the more widely used ones. The strcpy() function is used to copy
one string to another. The source string can be a variable or a string literal. Take the following
code, for example:
// set up a string to hold 29 characters
char buff[30];
// copy a string literal to the buffer
strcpy(buff, “This is a test.”);
// display it
cout <<>
// initialize a second string buffer
char buff2[] = “A second string.”;\
// copy the contents of this string to the first buffer
strcpy(buff, buff2);
cout <<>
Accidentally overwriting the end of a character array is even easier to do than with the numeric
arrays discussed earlier. For instance, imagine you had done the following:
char buff[10] = “A string”;
// later....
strcpy(buff, “This is a test.”); // oops!
Here we set up a character array to hold 10 characters and initially assigned a string that
requires 9 bytes (don’t forget about the terminating null). Later on, possibly forgetting how
large the array was, we copied a string to the buffer that requires 16 bytes, overwriting the
Function Description
NOTE
34 Day 1
array by 6 bytes. Six bytes of some memory location somewhere just got tromped on by our
little faux pas. Be careful when copying data to character arrays.
Another frequently used string function is sprintf(). This function allows you to build a
formatted string by mixing text and numbers together. Here is an example that adds two
numbers and then uses sprintf() to build a string to report the result:
char buff[20];
int x = 10 * 20;
sprintf(buff, “The result is: %d”, x);
cout <<>
When this section of code executes, the program will display this:
The result is: 200
In this example, the %d tells the sprintf() function, “An integer value will go here.” At the
end of the format string the variable x is inserted to tell sprintf() what value to put at that
location in the string (the contents of the variable x). sprintf() is a unique function in that
it can take a variable number of arguments. You must supply the destination buffer and the
format string, but the number of arguments that come after the format string is variable. Here
is an example of sprintf() that uses three additional arguments:
int x = 20;
int y = 5;
sprintf(buff, “%d + %d = %d”, x, y, x + y);
cout <<>
When this piece of code executes, the result displayed on the screen will be this:
20 + 5 = 25
The single slash is used in strings to indicate special characters. For
example, ‘\n’ is for a new line, and ‘\t’ represents a tab character. To
put an actual backslash character into a string, you must use a double
backslash:
strcpy(fileName, “c:\\windows\\system\\win.ini”);
Forgetting this simple fact has caused many programmers sleepless
nights trying to find a bug in their program. This is a very common
mistake to make. Don’t say I didn’t tell you!
sprintf() has a cousin called wsprintf() that is a Windows version of sprintf(). You might
see either of these two functions used in Windows programs. wsprintf() is functionally the
same as sprintf(), with one major difference: It does not allow you to put floating-point
NOTE
Getting Your Feet Wet 35
1
numbers in the formatted string. You can use either function in your C++Builder programs,
but sprintf() is preferred because it has full floating-point support (and it’s one less character
to type!). To get a real appreciation of what sprintf() can do for you, consult the C++Builder
online help.
Arrays of Strings
Not only can you have character arrays, but you can have an array of character arrays
(effectively an array of strings). That might sound complicated, but you have already seen this
type of array in the ARGSTEST program we looked at earlier. You can allocate this kind of array
as follows:
char strings[][20] = {
“This is string 1”,
“This is string 2”,
“This is string 3”,
“This is string 4”
};
Although you can use this type of string array, there are easier ways to handle arrays of strings
in C++Builder. (I’ll save that discussion for after you’ve had a chance to learn more about
C++Builder.)
If you are going to use arrays of strings extensively, you should look
into the Standard Template Library (STL). STL provides C++ classes
that allow you to store and manipulate arrays of strings much more
easily than is possible using C-style character arrays. STL also includes a
string class.
Summary
You’ve covered a lot of ground today. First you tinkered with the C++Builder IDE by
creating a GUI Hello World program. Following that you were introduced to console mode
applications where you created Hello World, Part II. After the initial playing around, you
were put to work learning the basics of C as a foundation to learning C++. You have learned
about the following C and C++ features:
n Variables
n Operators
n Data types
NOTE
36 Day 1
n Functions
n The main() function
n Arrays
n How strings are handled in C and C++
There is a lot of material to absorb in this chapter. Don’t feel bad if it didn’t all sink in. Go
back and review if you are unclear about anything presented in this chapter.
Workshop
The Workshop contains quiz questions to help you solidify your understanding of the
material covered and exercises to provide you with experience in using what you have learned.
You can find answers to the quiz questions in Appendix A, “Answers to Quiz Questions.”
Q&A
Q What’s the difference between a Win32 GUI application and a Win32
console-mode application?
A A GUI application is a traditional Windows program. It usually has a title bar,
menu, and window area. A console-mode application is a 32-bit application that
runs in an MS-DOS box in Windows. The console application looks like a DOS
program.
Q Do my functions have to take parameters and return values?
A Functions you write may take parameters and may return a value, but they are not
required to do either. Once a function has been written to return a value, you must
provide a return statement that returns a value or the compiler will issue a warning.
Q Can I assign a number containing decimal places to an integer data type
variable?
A Yes, but the decimal fraction will be dropped (not rounded) and only the whole
number portion will be assigned to the integer variable.
Q Will C++ make sure I don’t overwrite memory somewhere if I accidentally
write past the end of an array?
A No. One of the strengths of C++ is that it gives you the power to access memory
directly. With that power comes responsibility. It’s up to you, the programmer, to
be sure that the memory you are accessing is memory that your program owns. If
you accidentally overwrite memory that you are not supposed to have access to,
Getting Your Feet Wet 37
1
Windows will issue a general protection fault (GPF) or an access-violation error.
The GPF might come immediately, or it may not come until later when the
overwritten memory is used by another part of your program, by another program,
or by Windows itself.
Quiz
1. What is wrong with this program?
#include
#include
#pragma hdrstop
void displayText();
displayText()
{
cout << “Hello Bubba!” <<>
}
2. How many return values can a function return?
3. What does the strcpy() function do?
4. What value does a variable have when it is initially declared?
5. How many functions can a program have?
6. Can a function call another function?
7. What is wrong with this program?
#include
#include
#pragma hdrstop
int main(int argc, char** argv)
{
doSomething();
return 0;
}
void doSomething()
{
cout << “I’m doing something now” <<>
}
8. How many functions called main() can a program have?
9. Look at this line of code:
char buff[20];
How many characters can this string hold?
10. What is the index number of the first element of an array, 0 or 1?
38 Day 1
Exercises
1. Write a Windows GUI program that displays the words “Welcome to
C++Builder!” on the window when the program runs.
2. Rewrite the program you wrote in exercise 1 and change the displayed text to Hello
There! (Hint: You only have to change the Caption property of the Label component.)
3. Write a Windows console-mode application that outputs This is a test to the
screen.
4. Write a Windows console-mode application. In the program, declare two variables
and assign values to those variables. Multiply the two numbers together and display
the result on the screen.
5. Write a console-mode application that calls a function to display Function
entered, sir!! on the screen.
6. Write a console-mode application that takes an integer as a parameter, multiplies it
by itself, and returns the result.
7. Enter and compile the following program:
#include
#include
#include
#include
#pragma hdrstop
void getSqrRoot(char* buff, int x);
int main(int argc, char** argv)
{
int x;
char buff[30];
cout << “Enter a number: “;
cin >> x;
getSqrRoot(buff, x);
cout <<>
getch();
}
void getSqrRoot(char* buff, int x)
{
sprintf(buff, “The sqaure root is: %f”, sqrt(x));
}
What does the program do?
Wading In Deeper 39
2
Wading In Deeper
by Kent Reisdorph
You’ve now got a pretty good start on learning C++. In this chapter you will
continue to learn about the C++ language by examining more of the fundamentals
of C++ that have their roots in C. Today you will learn about
n The if and else keywords
n Loops: for, do, and do-while
n The switch statement
n Scope
n Structures

No comments:
Post a Comment