Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set a default argument from a previous argument?

Is it possible to use previous arguments in a functions parameter list as the default value for later arguments in the parameter list? For instance,

void f( int a, int b = a, int c = b ); 

If this is possible, are there any rules of use?

like image 390
bpw1621 Avatar asked Dec 10 '09 13:12

bpw1621


People also ask

Do default parameters have to be last?

Rule Details. This rule enforces default parameters to be the last of parameters.

Which function Cannot have a default argument?

Constructors cannot have default parameters.

What are the rules of default argument in C++?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.


1 Answers

The answer is no, you can't. You could get the behaviour you want using overloads:

void f(int a, int b, int c); inline void f(int a, int b) { f(a,b,b); } inline void f(int a)        { f(a,a,a); } 

As for the last question, C doesn't allow default parameters at all.

like image 110
Mike Seymour Avatar answered Oct 05 '22 06:10

Mike Seymour