| < Day Day Up > |
|
Example 5.2 gives the source code for another short C++ program. Although short, it has a little more meat to it than the minimal program discussed above.
Listing 5.2: Another C++ Program
1 /************************************************ 2 Simple C++ Program 3 ************************************************/ 4 5 #include <iostream> 6 7 using namespace std; 8 9 int main(){ 10 const int const_val = 100; 11 int i; 12 i = 10; 13 14 cout<<"This is a simple C++ program!"<<endl; 15 cout<<"The value of i is: "<<i<<endl; 16 cout<<"The value of const_val is: "<<const_val<<endl; 17 18 return 0; 19 }
Let us discuss example 5.2 line by line. The numbers 1 through 19 in italics to the left of the listing are line numbers and are not part of the source code.
Line 1 begins with the /* characters and is the start of a C-style comment. The comment proceeds to the end of line 3 which ends with the */ characters. Everything appearing between the /* and */ characters is ignored by the compiler. If you were to disassemble this code the comments would be omitted.
Line 5 begins with the preprocessor directive #include and names a library header file called iostream. The library header file named iostream is enclosed in the <> character pair telling the preprocessor how it should conduct its search for the iostream file. If you are using an older development environment you may have to use the filename iostream.h to access the iostream library.
Libraries, like iostream, are code modules that implement some type of functionality and can be incorporated into your programs. To gain access to a library the compiler must know where to find it and its header file must be included in the source code via an #include preprocessor directive.
Line 7 contains a using directive indicating that the namespace std (the standard namespace) is being used. This is required to gain access to various iostream objects. One iostream object, cout, is being used on lines 14, 15, and 16 to send stream output to the standard output device. The standard output device in this case is the computer screen.
Line 9 contains the start of the main() function. The body of the main() is comprised of everything appearing between the opening left brace { at the end of line 9, and closing right brace } on line 19.
Line 10 declares an integer constant named const_val and defines its value as 100. A constant is an object whose value is to remain unchanged during its lifetime. The keyword const is also used to prevent dumb programming mistakes or to enforce good program design.
Line 11 declares an integer variable named i. On line 12 i is assigned the value 10. Unlike a constant, a variable is an object whose value is allowed to change during its lifetime.
Lines 10 through 12, lines 14 through 16, and line 18 each contain a statement. Line 12 is an example of a statement that is also an expression.
| < Day Day Up > |
|