Can I set a default argument from a previous argument?

14,390

Solution 1

The answer is no, you can't. You could get the behaviour you want using overloads:

void f(int a, int b, int c);
inline void f(int a, int b) { f(a,b,b); }
inline void f(int a)        { f(a,a,a); }

As for the last question, C doesn't allow default parameters at all.

Solution 2

As a potential workaround, you could do:

const int defaultValue = -999; // or something similar

void f( int a, int b = defaultValue, int c = defaultValue )
{
    if (b == defaultValue) { b = a; }
    if (c == defaultValue) { c = b; }

    //...
}

Solution 3

This is not possible

Solution 4

No, you cannot do that.
You will surely get an error "Local variable may not appear in this context".

Solution 5

Your first idea might be to do something like this :

void something(int a, int b=-1, int c=-1){
    if(b == -1)
        b = a;
    if(c == -1)
        c = b;
}

I used -1 because this function only works with positive values. But what if someone uses my class and makes a mistake which ends up sending -1 to the method? It would still compile and execute, but the result would be unpredictable for the user. So the smart thing to do would be to remove any default argument and instead make a bunch of methods with the same name like this:

void something(int a, int b, int c){
    /* Do something with a, b and c */
}

void something(int a){
    something(a, a, a);
}

void something(int a, int b){
    something(a, b, b);
}

It doesn't really take much longer to code, and if someone uses it in a programming interface with auto-complete features, it will show the 3 possible prototypes.

Share:
14,390
bpw1621
Author by

bpw1621

Updated on June 05, 2022

Comments

  • bpw1621
    bpw1621 about 2 years

    Is it possible to use previous arguments in a functions parameter list as the default value for later arguments in the parameter list? For instance,

    void f( int a, int b = a, int c = b );
    

    If this is possible, are there any rules of use?