[DGD]varargs void foo(object bar)

Mikael Lind z94lind at mtek.chalmers.se
Mon Nov 30 14:50:51 CET 1998


On Mon, 30 Nov 1998, Frank Schmidt wrote:

> [...]
> 
> My problem: varargs with objects as parameters, and dealing with default
> values for objects.
> 
> Example: varargs void foo(object bar)
> 
> Now the call to this function can happen in four different scenarios:
> 1) foo()
> 2) foo(beer) /* when <beer> != 0 */
> 3) foo(beer) /* when <beer> == 0 */
> 4) foo(0)
> 
> The problem in this example is that there is absolutely NO way in foo()
> to detect that <bar> is a default parameter set-to-0 in 1). E.g.
> according to the tracelist, scenario 1), 3) and 4) are identical.

Use ellipsis, the "..." operator. This is will convert an argument list to
an array or vice versa, depending on the context.

varargs void foo(object bar...) {
    /* "bar" is an object array that is now containing all arguments
       supplied */

    int size;

    size = sizeof(bar);
    if (size > 1) {
        /* too many arguments supplied */

    } else if (size == 0) {
        /* scenario 1 */

    } else if (bar[0] != 0) {
        /* scenario 2 */

    } else {
        /* scenario 3 or 4 */

    }
}

As far as I know, it's currently impossible to distinguish scenario 3 from
scenario 4 from within the LPCd code. (And I don't see why you'd want to.)

There's certainly more to say about the design issue of giving a function
several different functionalities. Sometimes, it's more useful to split
the function into two (or even more) functions: 

void foo1(object bar) {
    if (bar == 0) {
        /*
         * scenario 3 or 4; in some cases considered an incorrect call, in
         * some other cases a default value could be assumed, and in still
         * other cases nothing is known for sure ;)
         */

    } else {
        /* scenario 2 */

    }
}

void foo2() {
    /* scenario 1 */

}

It all depends on what it is that you want to do.

[Insert a lengthy discussion on the benefits of argument-based function
call binding here, if you find it at all necessary.]

// Mikael

List config page:  http://list.imaginary.com/mailman/listinfo/dgd



More information about the DGD mailing list