Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ default a parameter to another parameter

Tags:

c++

parameters

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.

like image 686
Bernard Avatar asked Dec 05 '22 16:12

Bernard


2 Answers

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);
}
like image 59
Benjamin Lindley Avatar answered Jan 05 '23 12:01

Benjamin Lindley


It is not allowed.

The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in a default argument, even if they are not evaluated.

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

like image 21
Brian Bi Avatar answered Jan 05 '23 14:01

Brian Bi