< previous page page_73 next page >

Page 73
Analysis: A number is requested on lines 14 and 15 and printed on line 18, along with the local variable result. The function Doubler() is called on line 20, and the input value is passed as a parameter. The result will be assigned to the local variable result, and the values will be reprinted on lines 22 and 23.
On line 31, in the function Doubler(), the parameter is tested to see whether it is greater than 10,000. If it is not, the function returns twice the original number. If it is greater than 10,000, the function returns -1 as an error value.
The statement on line 35 is never reached, because whether or not the value is greater than 10,000, the function returns before it gets to line 35, on either line 32 or line 34. A good compiler will warn that this statement cannot be executed, and a good programmer will take it out!
Default Parameters
For every parameter you declare in a function prototype and definition, the calling function must pass in a value. The value passed in must be of the declared type. Thus, if you have a function declared as
long myFunction(int);
the function must, in fact, take an integer variable. If the function definition differs, or if you fail to pass in an integer, you will get a compiler error.
The one exception to this rule is if the function prototype declares a default value for the parameter. A default value is a value to use if none is supplied. The preceding declaration could be rewritten as
long myFunction (int x = 50);
This prototype says myFunction() returns a long and takes an integer parameter. If an argument is not supplied, use the default value of 50. Because parameter names are not required in function prototypes, this declaration could have been written as
long myFunction (int = 50);
The function definition is not changed by declaring a default parameter. The function definition header for this function would be
long myFunction (int x)
If the calling function did not include a parameter, the compiler would fill x with the default value of 50. The name of the default parameter in the prototype need not be the same as the name in the function header; the default value is assigned by position, not name.

 
< previous page page_73 next page >

If you like this book, buy it!