Topic: [Q] Default arguments in functions


Author: clamage@Eng.Sun.COM (Steve Clamage)
Date: 1995/12/16
Raw View
Martin Vorbeck <vorbeck@cs.sfu.ca> writes:

>and in Stroustrup's book "The C++ Programming Language" (Second Edition)
>on p. 535.

>Example:
>  int a = 1;
>  int f(int);
>  int g(int x = f(a)); // default argument: f(::a)

>  void h() {
>    a = 2;
>      {
>         int a = 3;
>         g();        // g(f(::a))
>      }
>   }
>
>But in Stroustrup's book, it says "... g will be called with the value
>f(2)..." while in the WP-draft it says "... g will be called with the
>value f(1) ..." ?!?

That's a typo in C++PL2. The comment f(::a) is correct, and the
valueof ::a is 1.


>2. Redeclaration or redefinition of a default argument is not allowed, ...

>Is there any fundamental problem in allowing such redeclarations or
>redefinitions, at least for the case where the expression for the
>default argument is exactly identical.

Then the problem is deciding whether they are identical. For example:

Are "1+1" and "2" identical? Presumably yes.

How about "sin(pi)" and "sin(2.0*pi)"? Mathematically they are
identical, but should the compiler be required to figure it out?

How about "2.1+2.1" and "4.0+0.2"? On some systems the result of
evaluating the two expressions might differ in the LSB's.

How about "x+1" and "1+x", where x is a variable? The compiler might
have to consider all equivalent reorderings of expressions.

If you allow redefinition as long as the token sequences are identical,
it means the compiler has to save token sequences in addition to
the information it really needs. Such a restrictive rule also doesn't
seem to have much benefit.


>3. Why are non-static data members not allowed in expression for default
>arguments of member functions? ...
> But wouldn't it be simple for a
>compiler, and clean semantically, to say the value for a is the one
>provided by the object foo of class X, for which the member function is
>being called?

Such a rule wouldn't work for static member functions, so it would
have to be restricted to nonstatic member functions.

We would also have to find some way to describe how the names in
the default expression are bound. The binding would be to an object
which is unspecified at the point of the declaration, which
complicates the explanation of the rule. Overall, it doesn't seem
worth the bother. After all, you can get the effect of default parameters
via overloading:

    class X {
 int k;
    public:
 f(int); // no default value
 f() { f(k); } // equivalent of f(int = this->k);
    };

--
Steve Clamage, stephen.clamage@eng.sun.com


---
[ comp.std.c++ is moderated.  Submission address: std-c++@ncar.ucar.edu.
  Contact address: std-c++-request@ncar.ucar.edu.  The moderation policy
  is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]