Tải bản đầy đủ - 0trang
Chapter 2. Getting Started Quickly: A Brief Overview of C++
Topics in this Chapter
The Basic Program Structure
Declarations and Definitions
Statements and Expressions
Functions and Function Calls
Dealing with Program Development Tools
In this chapter, I will briefly preview the basic programming constructs of the C++ language before
going on to discuss them in more depth in the chapters that follow. Because C++ is a large
language, anything that is "brief" is not going to cover much of the language, and anything that
indeed reviews the most important features of the language is not going to be "brief." I will try to
strike a reasonable compromise.
Studying a language like C++ feature by feature cannot give you a general picture that would
connect different features into a cohesive whole. Many features are intertwined and cannot be
discussed separately. This is why you need this preview. It will give you the first look at the most
important concepts and constructs of the C++ language, will enable you to write your first C++
programs, and will prepare you for studying these concepts and techniques in depth and in breadth.
The programs in this book are written using the ISO/ANSI standard C++. This version of the
language adds new features and also changes the syntax of some existing features. There are still
many compilers in use in industry that implement only some features of the new language. There
are too many different vendors and too many different compiler versions to discuss their
differences in implementing standard C++ in detail. Eventually, older compilers will be replaced by
newer versions. However, the industry will have to deal with the code written in prestandard C++
for many years to come. This old code will be supported by newer compilers as well, because
backward compatibility is one of the important goals of C++ design, and standard C++ adds new
file://///Administrator/General%20English%20Learning/it2002-7-6/core.htm (43 of 1187) [8/17/2002 2:57:44 PM]
features without making old features illegal. As a rule, I will cover new standard C++ syntax
without mentioning that explicitly. Where necessary, I will make reference to older ways of writing
code to make sure you can deal with legacy code with confidence.
The Basic Program Structure
Listing 2.1 shows the source code for your first C++ program. It welcomes you to the world of C++
(as most first programs in programming language books do). In addition, just to demonstrate more
features than a canonical "Hello World" program does, it makes some simple computations and
prints the result of raising the value of pi (3.1415926) to the power of two.
Example 2.1. Your first C++ program.
// preprocessor directive
// preprocessor directive
using namespace std;
// compiler directive
const double PI = 3.1415926;
// definition of a constant
// function returns integer
double x=PI, y=1, z;
// definitions of variables
cout << "Welcome to the C++ world!" << endl;
// function call
z = y + 1;
// assignment statement
y = pow(x,z);
// function call
cout << "In that world, pi square is " << y << endl;
cout << "Have a nice day!" << endl;
// return statement
// end of the function block
Do not worry if this program looks obscure. By the end of this chapter, you will understand every
detail here (and more).
Similar to other modern programming languages, C++ allows us to write instructions to the
computer in the form of human-readable source code. The C++ compiler translates the source code
into machine-readable object code. During program execution, machine language instructions are
executed one after another and produce the results.
Most computations are performed over values that are stored in computer memory. For our
purposes, we can think of computer memory as an array of locations with values. Locations cannot
be referred to by the values that are stored in them. They can be referred to either by their numeric
addresses (in the object code) or by their symbolic names (in the source code). For example, our
first C++ program contains the statement:
z = y + 1;
It instructs the computer to fetch the value that is stored at the location named y, increment that
file://///Administrator/General%20English%20Learning/it2002-7-6/core.htm (44 of 1187) [8/17/2002 2:57:44 PM]
value (without changing the contents at location y), and put the result into the location labeled z.
The real addresses of locations named y and z are specified in the executable code but not in the
source code; the programmer makes up these symbolic names but has no interest in what memory
addresses are assigned by the compiler to each name.
In real memory, integers, floating point numbers, and characters (text) are allocated different
numbers of bits and bytes, and their bit patterns are handled differently at run time. To generate
executable code correctly, the compiler has to understand the programmer's intent. This is why
before the statement z=y+1; can be executed, the compiler has to be told that y and z are indeed
symbolic names for locations in memory (and not for other things, e.g., functions) and that the
values stored in memory under these names are of the type double (one of C++ designations for
numbers with fractional parts).
So, most of the source code that the programmer writes either defines the objects that the program
manipulates (here, their names are x, y, z and others specified in #include and #define
directives) or describes what should be done with these objects (add, assign, pass as a parameter to
The source code for a C++ program can be an ordinary text file created by a text editor, like Emacs
or Vi on Unix, Edt on VMS, or by an Integrated Development Environment (IDE) on PC or Mac.
Here we save it as a file on the hard disk.
Usually, you give your source code files the names you see fit, but you are limited as to what file
name extension to use. Depending on the compiler, source files should be saved with file name
extension .cc, .cpp, or .cxx. Using other extensions is possible but less convenient. When standard
extensions are used, only the name of the source file has to be specified, and the development tools
append the extension automatically. Nonstandard extensions are allowed (and frowned on) but they
have to be specified explicitly.
The source file can define several functions (our first C++ program has only one; its name is main).
The program can consist of several source files (this program has only one). Each source file has to
be compiled, producing the object file. Most environments require that the compiled program
(object files) be linked before it can be executed. (You will learn more about that later in the
chapter.) Figure 2-1 shows the output of execution of our first C++ program.
Figure 2.1. Output of our first C++ program produced by a Microsoft compiler.
file://///Administrator/General%20English%20Learning/it2002-7-6/core.htm (45 of 1187) [8/17/2002 2:57:44 PM]
This output was produced by the executable file generated by the Microsoft Visual C++ compiler,
Professional Edition version 6.0. It is a part of Microsoft Development Studio, which integrates
several development tools in the same package. The program was called by the Development
Studio. The last line of the output is generated by the compiler, not by the program. Otherwise, the
window would be removed from the screen immediately after program termination, and the user
would not be able to inspect the program output. Older versions of the Microsoft compiler do not
add this message, but they do not remove the window from the screen either¡Xthe user has to do
that. The program can also be run as a stand-alone application directly from the DOS prompt. In
that case, the last line does not appear. Figure 2-2 shows the result of running this program from the
Figure 2.2. Output of our first C++ program run from the DOS command prompt.
The numeric output on different machines might be somewhat different as well. This depends on
the default setting for the number of digits in the output. C++ allows the programmer to explicitly
specify the format of the output, so that it does not depend on the compiler settings, but it is rather
complex and does not belong to this preview. You will see the examples of doing that later.
Our first C++ program demonstrates the following components that should be present in any C++
declarations and definitions
statements and expressions
file://///Administrator/General%20English%20Learning/it2002-7-6/core.htm (46 of 1187) [8/17/2002 2:57:45 PM]
functions and function calls
In the following sections I'll discuss the use of each kind of program component in more detail.
In most other languages, what you write in the source file is what the compiler sees during
compilation. This is not the case in C++. The compiler is not the first tool that deals with the source
code on its way to becoming an executable program. The first tool that processes the source code is
the preprocessor. What is this? Well, it is an interesting invention that C++ inherited from C. Its
goal is to decrease the amount of source code that the programmer writes during development (or
reads during debugging or maintenance).
The preprocessor processes the source file and passes the results of processing to the compiler for
compilation. Most of the program statements are ignored by the preprocessor and are passed to the
compiler unmodified. The preprocessor pays attention only to preprocessor directives (and to
statements that are related to them).
The preprocessor directives start with a '#' and take up the whole line. You cannot put more than
one directive on a single source line. If the directive does not fit into one source line, it can be
continued on the next line, but the previous line should be ended by a special continuation
character, the escape character '\'. The pound sign '#' should be the first character on the line. What
about the free format of C++ source code? In the previous chapter, I told you that you can format
C++ code the way you (and not the compiler) see fit. Well, formally, preprocessor directives are
not part of the C++ (or C) language, and the preprocessor is not part of the compiler.
In practice, of course, you cannot write even a simple C++ program without using preprocessor
directives, but in theory, these directives are not part of the language! In practice, it is the compiler
vendors that supply the preprocessors, but in theory, compilers and preprocessors are not related.
Lately, compiler vendors have relaxed the rule: The '#' does not have to be the first character on the
line, but it should be the first nonblank character.
Listing 2.1 uses two #include preprocessor directives. The #include directive causes direct text
substitution: The preprocessor fetches the whole file whose name is specified as the directive
argument and replaces the directive by the contents of the file taken verbatim. This can be used to
combine several source files into one source file that is then compiled as a whole. The most popular
use of this directive is to include function headers that describe functions used by the source code.
The names of these header files are put in the angle brackets to indicate to the preprocessor that it
has to search for this file in the standard directory where the compiler stores its header files. For
example, the #include directives used in the first program specify two header files. The first one is
file://///Administrator/General%20English%20Learning/it2002-7-6/core.htm (47 of 1187) [8/17/2002 2:57:45 PM]
needed for using the function pow(), the second one is needed for using the operator << and the
object cout. We will learn more about functions, operators, and objects later. This is just one of
the examples of the complexity of C++¡Xit is impossible to discuss even a simple program without
using components that cannot be understood without learning much more than a simple program.