Sams Teach Yourself C++ in 21 Days

(singke) #1
The Anatomy of a C++ Program 27

2


Line 3 begins the actual program with a function named main(). Every C++ program has
a main()function. A function is a block of code that performs one or more actions.
Usually, functions are invoked or called by other functions, but main()is special. When
your program starts,main()is called automatically.
main(), like all functions, must state what kind of value it returns. The return value type
for main()in HELLO.cppis int, which means that this function returns an integer to the
operating system when it completes. In this case, it returns the integer value 0 , as shown
on line 6. Returning a value to the operating system is a relatively unimportant and little
used feature, but the C++ standard does require that main()be declared as shown.

Some compilers let you declare main()to return void. This is no longer legal
C++, and you should not get into bad habits. Have main()return int, and
simply return 0 as the last line in main().

CAUTION


Some operating systems enable you to test the value returned by a program.
The convention is to return 0 to indicate that the program ended normally.

NOTE


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 coutis used to print a message to the screen. You’ll learn about objects in
general on Day 6, “Understanding Object-Oriented Programming,” and coutand its
related object cinin detail on Day 17, “Working with Streams.” These two objects,cin
and cout, are used in C++ to handle input (for example, from the keyboard) and output
(for example, to the console), respectively.
coutis an object provided by the standard library. A library is a collection of classes.
The standard library is the standard collection that comes with every ANSI-compliant
compiler.
You designate to the compiler that the coutobject you want to use is part of the standard
library by using the namespace specifier std. Because you might have objects with the
same name from more than one vendor, C++ divides the world into “namespaces.” A
namespace is a way to say “when I say cout, I mean the coutthat is part of the standard
Free download pdf