Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a C++ default argument be initialized with another argument? [duplicate]

Tags:

c++

For a default argument in C++, does the value need to be a constant or will another argument do?

That is, can the following work?

RateLimiter(unsigned double rateInPermitsPerSecond,              unsigned int maxAccumulatedPermits = rateInPermitsPerSecond); 

Currently I am getting an error:

RateLimiter.h:13: error: ‘rateInPermitsPerSecond’ was not declared in this scope

like image 633
user1918858 Avatar asked May 19 '16 22:05

user1918858


People also ask

Can you set default arguments in C?

Yes. :-) But not in a way you would expect. Unfortunately, C doesn't allow you to overload methods so you'd end up with two different functions. Still, by calling f2, you'd actually be calling f1 with a default value.

Which is the correct condition for the default arguments?

Which is the correct condition for the default arguments? Explanation: The default arguments must be declared at last in the argument list. This is to ensure that the arguments doesn't create ambiguity.

CAN default arguments be skipped?

It's not possible to skip it, but you can pass the default argument using ReflectionFunction .

Can we give default value to arguments?

In addition to passing arguments to functions via a function call, you can also set default argument values in Python functions. These default values are assigned to function arguments if you do not explicitly pass a parameter value to the given argument. Parameters are the values actually passed to function arguments.


1 Answers

Another argument cannot be used as the default value. The standard states:

8.3.6 Default arguments
...
9 A default argument is evaluated each time the function is called with no argument for the corresponding parameter. 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.

and illustrates it with the following sample:

int f(int a, int b = a); // error: parameter a                          // used as default argument 
like image 164
AlexD Avatar answered Oct 20 '22 14:10

AlexD