Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why C++ does not allow function parameters used for default values latter parameters?

This is a follow-up on this question. The code in the OP question there looked quite reasonable and unambiguous to me. Why does not C++ allow using former parameters to define default values of latter parameters, something like this:

int foo( int a, int b = a );

Also, at least in C++11 declared types of parameters can be used to determine the return type, so it's not unheard of to use function parameters in similar manner:

auto bar( int a ) -> decltype( a );

Thus the question: what are the reason(s) why the above declaration of foo is not allowed?

like image 983
Michael Avatar asked Jul 30 '15 00:07

Michael


People also ask

Can C functions have default parameters?

Generally no, but in gcc You may make the last parameter of funcA() optional with a macro.

Is it possible to give a default value to a function parameter?

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

Can all the parameters of a function can be default parameters?

All the parameters of a function can be default parameters.

Which parameter Cannot have a default value?

An IN OUT parameter cannot have a default value. An IN OUT actual parameter or argument must be a variable.


1 Answers

For one thing, this would require that a is evaluated before b, but C++ (like C) does not define the order of evaluation for function parameters.

You can still get the effect you want by adding an overload:

int foo(int a, int b)
{ /* do something */ }

int foo(int a)
{ return foo(a, a); }
like image 172
Bo Persson Avatar answered Nov 09 '22 14:11

Bo Persson