Placing the using Directive in Multifunction Programs

Notice that Listing 2.5 places a using directive in each of the two functions:

using namespace std;

This is because each function uses cout and thus needs access to the cout definition from the std namespace.

There’s another way to make the std namespace available to both functions in Listing 2.5, and that’s to place the directive outside and above both functions:

// ourfunc1.cpp -- repositioning the using directive
#include <iostream>
using namespace std; // affects all function definitions in this file
void simon(int);

int main()
{
    simon(3);
    cout << "Pick an integer: ";
    int count;
    cin >> count;
    simon(count);
    cout << "Done!" << endl;
    return 0;
}

void simon(int n)
{
    cout << "Simon says touch your toes " << n << " times." << endl;
}

The current prevalent philosophy is that it’s preferable to be more discriminating and limit access to the std namespace to only those functions that need access. For example, in Listing 2.6, only main() uses cout, so there is no need to make the std namespace available to the stonetolb() function. Thus, the using directive is placed inside the main() function only, limiting std namespace access to just that function.

In summary, you have several choices for making std namespace elements available to a program. Here are some:

• You can place the following above the function definitions in a file, making all the contents of the std namespace available to every function in the file:

using namespace std;

• You can place the following in a specific function definition, making all the contents of the std namespace available to that specific function:

using namespace std;

• Instead of using

using namespace std;

• you can place using declarations like the following in a specific function definition and make a particular element, such as cout, available to that function:

using std::cout;

• You can omit the using directives and declarations entirely and use the std:: prefix whenever you use elements from the std namespace:

std::cout << "I'm using cout and endl from the std namespace" << std::endl;

Summary

A C++ program consists of one or more modules called functions. Programs begin executing at the beginning of the function called main() (all lowercase), so you should always have a function by this name. A function, in turn, consists of a header and a body. The function header tells you what kind of return value, if any, the function produces and what sort of information it expects arguments to pass to it. The function body consists of a series of C++ statements enclosed in paired braces ({}).

C++ statement types include the following:

Declaration statement— A declaration statement announces the name and the type of a variable used in a function.

Assignment statement— An assignment statement uses the assignment operator (=) to assign a value to a variable.

Message statement— A message statement sends a message to an object, initiating some sort of action.

Function call— A function call activates a function. When the called function terminates, the program returns to the statement in the calling function immediately following the function call.

Function prototype— A function prototype declares the return type for a function, along with the number and type of arguments the function expects.

Return statement— A return statement sends a value from a called function back to the calling function.

A class is a user-defined specification for a data type. This specification details how information is to be represented and also the operations that can be performed with the data. An object is an entity created according to a class prescription, just as a simple variable is an entity created according to a data type description.

C++ provides two predefined objects (cin and cout) for handling input and output. They are examples of the istream and ostream classes, which are defined in the iostream file. These classes view input and output as streams of characters. The insertion operator (<<), which is defined for the ostream class, lets you insert data into the output stream, and the extraction operator (>>), which is defined for the istream class, lets you extract information from the input stream. Both cin and cout are smart objects, capable of automatically converting information from one form to another according to the program context.

C++ can use the extensive set of C library functions. To use a library function, you should include the header file that provides the prototype for the function.

Now that you have an overall view of simple C++ programs, you can go on in the next chapters to fill in details and expand horizons.

Chapter Review

You can find the answers to the chapter review at the end of each chapter in Appendix J, “Answers to Chapter Review.”

1. What are the modules of C++ programs called?

2. What does the following preprocessor directive do?

#include <iostream>

3. What does the following statement do?

using namespace std;

4. What statement would you use to print the phrase “Hello, world” and then start a new line?

5. What statement would you use to create an integer variable with the name cheeses?

6. What statement would you use to assign the value 32 to the variable cheeses?

7. What statement would you use to read a value from keyboard input into the variable cheeses?

8. What statement would you use to print “We have X varieties of cheese,” where the current value of the cheeses variable replaces X?

9. What do the following function prototypes tell you about the functions?

int froop(double t);
void rattle(int n);
int prune(void);

10. When do you not have to use the keyword return when you define a function?

11. Suppose your main() function has the following line:

cout << "Please enter your PIN: ";

And suppose the compiler complains that cout is an unknown identifier. What is the likely cause of this complaint, and what are three ways to fix the problem?

Programming Exercises

1. Write a C++ program that displays your name and address (or if you value your privacy, a fictitious name and address).

2. Write a C++ program that asks for a distance in furlongs and converts it to yards. (One furlong is 220 yards.)

3. Write a C++ program that uses three user-defined functions (counting main() as one) and produces the following output:

Three blind mice
Three blind mice
See how they run
See how they run

One function, called two times, should produce the first two lines, and the remaining function, also called twice, should produce the remaining output.

4. Write a program that asks the user to enter his or her age. The program then should display the age in months:

Enter your age: 29

Your age in months is 384.

5. Write a program that has main() call a user-defined function that takes a Celsius temperature value as an argument and then returns the equivalent Fahrenheit value. The program should request the Celsius value as input from the user and display the result, as shown in the following code:

Please enter a Celsius value: 20
20 degrees Celsius is 68 degrees Fahrenheit.

For reference, here is the formula for making the conversion:

Fahrenheit = 1.8 × degrees Celsius + 32.0

6. Write a program that has main() call a user-defined function that takes a distance in light years as an argument and then returns the distance in astronomical units. The program should request the light year value as input from the user and display the result, as shown in the following code:

Enter the number of light years: 4.2
4.2 light years = 265608 astronomical units.

An astronomical unit is the average distance from the earth to the sun (about 150,000,000 km or 93,000,000 miles), and a light year is the distance light travels in a year (about 10 trillion kilometers or 6 trillion miles). (The nearest star after the sun is about 4.2 light years away.) Use type double (as in Listing 2.4) and this conversion factor:

1 light year = 63,240 astronomical units

7. Write a program that asks the user to enter an hour value and a minute value. The main() function should then pass these two values to a type void function that displays the two values in the format shown in the following sample run:

Enter the number of hours: 9
Enter the number of minutes: 28
Time: 9:28

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.218.157