Functions with Empty Parameter Lists

In C++, an empty parameter list is specified by writing either void or nothing at all in parentheses. The prototype

void print();

specifies that function print does not take arguments and does not return a value. Figure 6.17 demonstrates both ways to declare and use functions with empty parameter lists.

Figure 6.17. Functions that take no arguments.

(This item is displayed on page 273 in the print version)

 1 // Fig. 6.17: fig06_17.cpp
 2 // Functions that take no arguments.
 3 #include 
 4 using std::cout;
 5 using std::endl;
 6
 7 void function1(); // function that takes no arguments 
 8 void function2( void ); // function that takes no arguments
 9
10 int main()
11 {
12 function1(); // call function1 with no arguments
13 function2(); // call function2 with no arguments
14 return 0; // indicates successful termination
15 } // end main
16
17 // function1 uses an empty parameter list to specify that
18 // the function receives no arguments
19 void function1()
20 {
21 cout << "function1 takes no arguments" << endl;
22 } // end function1
23
24 // function2 uses a void parameter list to specify that
25 // the function receives no arguments
26 void function2( void )
27 {
28 cout << "function2 also takes no arguments" << endl;
29 } // end function2
 
 function1 takes no arguments
 function2 also takes no arguments
 

Portability Tip 6.2

The meaning of an empty function parameter list in C++ is dramatically different than in C. In C, it means all argument checking is disabled (i.e., the function call can pass any arguments it wants). In C++, it means that the function explicitly takes no arguments. Thus, C programs using this feature might cause compilation errors when compiled in C++.


Common Programming Error 6.13

C++ programs do not compile unless function prototypes are provided for every function or each function is defined before it is called.






C++ How to Program
C++ How to Program (5th Edition)
ISBN: 0131857576
EAN: 2147483647
Year: 2004
Pages: 627
Simiral book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net