c++parameters

C++ default a parameter to another parameter


Can I use the first parameter as a default for the second parameter, like this?

int do_something(int a, int b = a + 1){
    /* ... */
}

My compiler doesn't seem to like it, so perhaps it's not allowed.


Solution

  • Your question has already been answered (it is not allowed), but in case you didn't realize, the workaround is trivial with function overloading.

    int do_something(int a, int b){
        /* ... */
    }
    
    int do_something(int a) {
        return do_something(a, a + 1);
    }