|
|
|
|
|
|
|
two variables because each is visible only inside its own block. Also, ch should be declared locally in CountChars, of course, because that is the only place where it is used. |
|
|
|
|
|
|
|
|
The Trouble program also demonstrates one common exception to the rule of not accessing global variables. Technically, cin and cout are global variables declared in the header file iostream.h. Function CountChars reads and writes directly to these streams. To be absolutely correct, cin and cout should be passed as reference parameters to the function. However, cin and cout are fundamental I/O facilities supplied by the standard library, and it is conventional for C++ functions to access them directly. |
|
|
|
|
|
|
|
|
Contrary to what you might think, it is also acceptable to reference named constants globally. Because the values of global constants cannot be changed while the program is running, no side effects can occur. You have seen numerous examples of programs using global constants, such as the LumberYard program of Chapter 5 and the TempStat and Invoice programs of Chapter 6, to name a few. |
|
|
|
|
|
|
|
|
There are two advantages to referencing constants globally: 1) ease of change and 2) consistency. If we have to change the value of a constant, it's easier to change only one global declaration than to change a local declaration in every function. By declaring a constant in only one place, we also ensure that all parts of the program use exactly the same value. |
|
|
|
|
|
|
|
|
This is not to say that you should declare all constants globally. If a constant is needed in only one function, then it makes sense to declare it locally within that function. |
|
|
|
|
|
|
|
|
At this point, you may want to turn to the first two problem-solving case studies at the end of this chapter. These case studies further illustrate the interface design process and the use of value and reference parameters. |
|
|
|
|
|
|
|
|
Value-Returning Functions |
|
|
|
|
|
|
|
|
In Chapter 7 and the first part of this chapter, we have been writing our own void functions. We now look at the second kind of subprogram in C++, the value-returning function. You already know several value-returning functions supplied by the C++ standard library: sqrt, abs, fabs, and others. From the caller's perspective, the main difference between void functions and value-returning functions is the way in which they are called. A call to a void function is a complete statement; a call to a value-returning function is part of an expression. |
|
|
|
|
|
|
|
|
From a design perspective, value-returning functions are used when there is only one result returned by a function and that result is to be used directly in an expression. For example, suppose we are writing a program that calculates a prorated refund of tuition for students who withdraw in the |
|
|
|
|
|