Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should default parameters be added last in C++ functions?

Why should default parameters be added last in C++ functions?

like image 347
yesraaj Avatar asked Sep 11 '25 08:09

yesraaj


2 Answers

To simplify the language definition and keep code readable.

void foo(int x = 2, int y);

To call that and take advantage of the default value, you'd need syntax like this:

foo(, 3);

Which was probably felt to be too weird. Another alternative is specifying names in the argument list:

foo(y : 3);

A new symbol would have to be used because this already means something:

foo(y = 3); // assign 3 to y and then pass y to foo.

The naming approach was considered and rejected by the ISO committee because they were uncomfortable with introducing a new significance to parameter names outside of the function definition.

If you're interested in more C++ design rationales, read The Design and Evolution of C++ by Stroustrup.

like image 167
Daniel Earwicker Avatar answered Sep 13 '25 01:09

Daniel Earwicker


If you define the following function:

void foo( int a, int b = 0, int c );

How would you call the function and supply a value for a and c, but leave b as the default?

foo( 10, ??, 5 );

Unlike some other languages (eg, Python), function arguments in C/C++ can not be qualified by name, like the following:

foo( a = 10, c = 5 );

If that were possible, then the default arguments could be anywhere in the list.

like image 38
Daniel Paull Avatar answered Sep 13 '25 00:09

Daniel Paull