Sams Teach Yourself C++ in 21 Days

(singke) #1
LISTING2.1 HELLO.cppDemonstrates the Parts of a C++ Program
1: #include <iostream>
2:
3: int main()
4: {
5: std::cout << “Hello World!\n”;
6: return 0;
7: }

Hello World!

On line 1, the file iostreamis included into the current file.

Here’s how that works: The first character is the #symbol, which is a signal to a program
called the preprocessor. Each time you start your compiler, the preprocessor is run first.
The preprocessor reads through your source code, looking for lines that begin with the
pound symbol (#) and acts on those lines before the compiler runs. The preprocessor is
discussed in detail on Day 21, “What’s Next.”
The command #includeis a preprocessor instruction that says, “What follows is a file-
name. Find that file, read it, and place it right here.” The angle brackets around the file-
name tell the preprocessor to look in all the usual places for this file. If your compiler is
set up correctly, the angle brackets cause the preprocessor to look for the file iostream
in the directory that holds all the include files for your compiler. The file iostream
(Input-Output-Stream) is used by cout, which assists with writing to the console. The
effect of line 1 is to include the file iostreaminto this program as if you had typed it in
yourself.

OUTPUT


26 Day 2


ANALYSIS

The preprocessor runs before your compiler each time the compiler is
invoked. The preprocessor translates any line that begins with a pound sym-
bol (#) into a special command, getting your code file ready for the compiler.

NOTE

Not all compilers are consistent in their support for #includes that omit the
file extension. If you get error messages, you might need to change the
include search path for your compiler, or add the extension to the #include.

NOTE
Free download pdf