views:

458

answers:

7

I was unable to find a clear answer to this although that might be because I was not using the proper search terms so please redirect me if that is the case. 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? Any difference between C and C++?

+12  A: 

No, that is not legal C++. This is specified in section 8.3.6/9 of the C++ Standard:

Default arguments are evaluated each time the function is called. The order of evaluation of function argu- ments is unspecified. Consequently, parameters of a function shall not be used in default argument expres- sions, even if they are not evaluated.

and:

int f(int a, int b = a); // error: parameter a used as default argument

And C89 at least does not support default parameter values.

anon
+3  A: 

This is not possible

Andreas Brinck
+4  A: 

No, you cannot do that.
You will surely get an error "Local variable may not appear in this context".

Prasoon Saurav
+3  A: 

As a potential workaround, you could do:

const int defaultValue = -999; // or something similar

void f( int a, int b = defaultValue, int c = defaultValue )
{
    if (b == defaultValue) { b = a; }
    if (c == defaultValue) { c = b; }

    //...
}
e.James
+1 Was going to write this as well
Andreas Brinck
Thank you. Looking at the other answers, I think Mike Seymour's approach is even better.
e.James
+25  A: 

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.

Mike Seymour
+1 Probably the best solution
Andreas Brinck
Thank you for the workaround.
bpw1621
+1  A: 

I do not think you can do that as that is an illegal syntax. But however, consult the C99 standard in pdf format (n1136.pdf).

However, you may get around this by using static as in declaring the variables static and using them within the function f

static int global_a;

/* In some other spot where you are calling f(), do this beforehand */
/* global_a = 4; f(); */

void f(void){
   int a = global_a;
   b = c = a;
   /* ..... */
}

Kudos to Michael Burr for pointing out my error! :)

It sounds like you need to rethink your code and change it around for something like that.

Hope this helps, Best regards, Tom.

tommieb75
I don't follow - if you do something like this, there's no reason to pass parameters at all since they aren't being used.
Michael Burr
@Michael Burr: Yes you are correct...my bad! Meh...I will edit this accordingly and mention your input. Thanks! :)
tommieb75
A: 

I'm sorry if I'm missing something, but why don't you just do

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

?

Christian Severin