< previous page page_21 next page >

Page 21
Line by Line Analysis
Line 3 begins the actual program with a function named main(). Every C++ program has a main() function. In general, a function is a block of code that performs one or more actions. Functions are invoked, (some programmers say they are called) by other functions, but main() is special. When your program starts, main() is called automatically.
The function main(), like all functions, must state what kind of value it will return. Once again, main() is special; it will always return int. Returning a value from a function will be discussed in detail in Hour 4, Expressions and Statements.
All functions begin with an opening brace ({) and end with a closing brace (}). The braces for the main() function are on lines 4 and 7. Everything between the opening and closing braces is considered a part of the function.
The meat and potatoes of this program is on line 5. The object cout is used to print a message to the screen. We'll cover objects in general beginning in Hour 7, More About Classes. The object cout and its related object cin are provided by your compiler vendor and enable the system to write to the screen and read in from the keyboard.
Here's how cout is used: Write the word cout followed by the output redirection operator (<<). You create the output redirection operator by keyboarding shift-comma twice. Whatever follows the output redirection operator is written to the screen. If you want a string of characters to be written, be sure to enclose them in double quotes (") as shown on line 5.
Note, a text string is a series of printable characters.
The final two characters, \n, tell cout to put a new line after the words Hello World!
On line 6 we return the value 0 to the operating system. On some systems this is used to signal to the operating system success or failure; the convention is to return 0 for success and any other number for failure. On modern windowing machines, this value is almost never used, and so all the programs in this book will return the value 0.
The main() function ends on line 7 with the closing brace.
Comments
When you are writing a program, it is always clear and self-evident what you are trying to do. Funny thing, thougha month later, when you return to the program, it can be quite confusing and unclear. I'm not sure how that confusion creeps into your program, but it's always there.

 
< previous page page_21 next page >

If you like this book, buy it!