Default argument values

bearophile bearophileHUGS at lycos.com
Thu May 20 15:45:17 PDT 2010


Adam Ruppe:

> void func(Whatever* options = null) {
>     if(options is null)
>          options = Whatever(default blah blah);
> }
> 
> (substitute null for any invalid amount for the parameter. I recently
> did some timezone functions that used int.min as the default offset,
> meaning load it from the global.)
> 
> If I want to change the Whatever default, I change it there and it
> still works out. Nothing fancy required.

In ShedSkin (a kind of Python compiler) I plan to do something like that automatically. The compiler creates a nullable value for each value that has a default, plus the if+assign inside the function. The nullable is done compactly, with an extra uint argument that encodes what arguments are actually given or what ones are not given and need to be initialized inside the function.

So if you write code like this:


void foo(int x, string s="hello", int y=10) {
}
void main() {
    foo(1, "red", 2);
    foo(3, "green");
    foo(4);
}



It is syntax sugar for:

void foo(int x, string s, int y, uint nDefaults) {
    if (nDefaults >= 1)
        y = 10;
    if (nDefaults >= 2)
        s = "hello";
}
void main() {
    foo(1, "red", 2, 0);
    foo(3, "green", int.init, 1);
    foo(4, string.init, int.init, 2);
}


This is not exactly like the Python semantics, because in Python default arguments are set at function definition time (defining a function is an operation).
Even if this can be acceptable for ShedSkin, probably it's not a good solution for a almost-system language as D.

-----------------

Brad Roberts:

>Converting these to helpers functions will result in a tiny little function that will be inlined, so, right back to the same basic problem.<

I am not sure, but in Scala they can be virtual functions, so the HotSpot inlines/deinlines them dynamically and as needed to keep the code both fast and safe all the time.

Thank you for all the answers,
bye,
bearophile


More information about the Digitalmars-d mailing list