Sams Teach Yourself C++ in 21 Days

(singke) #1
namespace. In this case, rather than writing using std::cout;, you would simply write
using namespace std;, as shown in Listing 2.4.

LISTING2.4 Using thenamespaceKeyword
1: // Listing 2.4 - using namespace std
2: #include <iostream>
3: int main()
4: {
5: using namespace std;
6:
7: cout << “Hello there.\n”;
8: cout << “Here is 5: “ << 5 << “\n”;
9: cout << “The manipulator endl “;
10: cout << “writes a new line to the screen.”;
11: cout << endl;
12: cout << “Here is a very big number:\t” << 70000;
13: cout << endl;
14: cout << “Here is the sum of 8 and 5:\t”;
15: cout << 8+5 << endl;
16: cout << “Here’s a fraction:\t\t”;
17: cout << (float) 5/8 << endl;
18: cout << “And a very very big number:\t”;
19: cout << (double) 7000 * 7000 << endl;
20: cout << “Don’t forget to replace Jesse Liberty “;
21: cout << “with your name...\n”;
22: cout << “Jesse Liberty is a C++ programmer!\n”;
23: return 0;
24: }

Again, the output is identical to the earlier versions of this program. The advan-
tage to writing using namespace std;is that you do not have to specifically
designate the objects you’re actually using (for example,coutand endl;). The disadvan-
tage is that you run the risk of inadvertently using objects from the wrong library.
Purists prefer to write std::in front of each instance of coutor endl. The lazy prefer to
write using namespace std;and be done with it. In this book, most often the individual
items being used are declared, but from time to time each of the other styles are pre-
sented just for fun.

Commenting Your Programs..................................................................................


When you are writing a program, your intent is always clear and self-evident to you.
Funny thing, though—a month later, when you return to the program, it can be quite con-
fusing and unclear. No one is ever certain how the confusion creeps into a program, but it
nearly always does.

32 Day 2


ANALYSIS
Free download pdf