C ++ default parameter for another parameter

Is it possible to use the first default parameter for the second parameter, for example?

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

My compiler does not seem to like it, so this may not be allowed.

+4
source share
3 answers

Your question has already been answered (this is not resolved), but in case you do not understand this, 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);
}
+11
source

Is not allowed.

The evaluation order of the function arguments is not specified. Therefore, function parameters should not be used in the default argument, even if they are not evaluated.

(from [dcl.fct.default] / 9 in C ++ 14)

+9
source

U,

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

But the value of b will not change after the function is executed. Passing b by reference will work. (int & b)

-5
source

Source: https://habr.com/ru/post/1653560/


All Articles