Datasheet
The Obligatory Hello, World
In all its glory, the following code is the simplest C++ program you’re likely to encounter.
// helloworld.cpp
#include <iostream>
int main(int argc, char** argv)
{
std::cout << “Hello, World!” << std::endl;
return 0;
}
This code, as you might expect, prints the message Hello, World! on the screen. It is a simple program
and unlikely to win any awards, but it does exhibit several important concepts about the format of a
C++ program.
Comments
The first line of the program is a comment, a message that exists for the programmer only and is ignored
by the compiler. In C++, there are two ways to delineate a comment. In the preceding example, two
slashes indicate that whatever follows on that line is a comment.
// helloworld.cpp
The same behavior (this is to say, none) would be achieved by using a C-style comment, which is also
valid in C++. C-style comments start with
/* and end with */. In this fashion, C-style comments are
capable of spanning multiple lines. The code below shows a C-style comment in action (or, more appro-
priately, inaction).
/* this is a multiline
* C-style comment. The
* compiler will ignore
* it.
*/
Comments are covered in detail in Chapter 7.
Preprocessor Directives
Building a C++ program is a three-step process. First, the code is run through a preprocessor, which recog-
nizes metainformation about the code. Next, the code is compiled, or translated into machine-readable
object files. Finally, the individual object files are linked together into a single application. Directives that
are aimed at the preprocessor start with the
# character, as in the line #include <iostream> in the
previous example. In this case, an include directive tells the preprocessor to take everything from the
iostream header file and make it available to the current file. The most common use of header files is to
declare functions that will be defined elsewhere. Remember, a declaration tells the compiler how a func-
tion is called. A definition contains the actual code for the function. The iostream header declares the
input and output mechanisms provided by C++. If the program did not include it, it would be unable to
perform its only task of outputting text.
2
Chapter 1
04_574841 ch01.qxd 12/15/04 3:39 PM Page 2