9.12 DEFAULT ARGUMENTS FOR C FUNCTIONS


9.12 DEFAULT ARGUMENTS FOR C++ FUNCTIONS

If at the time of defining a C++ function it is known that a parameter of the function is likely to take on a certain value, then that value can be embedded in the function header itself using standard initialization syntax. For example, if for a function foo(int x, int y), the parameter y will in most cases be set to, say, 100, we could define the function in the following manner:

      int foo(int x, int y = 100) {          // function body      } 

The value of 100 is a default argument for the parameter y of the function. With such a definition, we could make the following types of invocations of this function:

      foo(23);           // x will be set to 23 and y to 100      foo(34, 200);      // x will be set to 34 and y to 200 

Default arguments can only be supplied for the trailing parameters of a function. To explain this point, consider a function of three argument int bar (int x, int y, char* p). We could supply a default argument for the parameter p, as in the definition:

      int bar(int x, int y, char* p = 0) {         // body of function goes here      } 

or we could supply default arguments for the last two parameters, y and p, as in

      int bar(int x, int y = 37, char* p = 0) {         // body of function goes here      } 

or we could supply default arguments for all three parameters, as in

      int bar(int x = 29, int y = 37, char* p = 0) {         // body of function goes here      } 

but, if we do not give a default argument to the last parameter p, we are not allowed to assign default arguments to either x or y. For example, the following definition would not be acceptable to the compiler

      int bar(int x, int y = 37, char* p) {       // WRONG         // body of function goes here      } 

The reason that only trailing parameters can be given default arguments is that the argument list in an invocation of such a function is resolved by position. If it were permissible to give a default argument to a non-trailing parameter, the compiler would not be able to figure out as to which argument to assign to what parameter.




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

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