Default Parameters Set To Other Parameters

1
2
3
4
void Function(int p1, int p2);    //Here is a simple function
void Function(int p1, int p2=5);  //Here is a simple function with a default parameter

void Function(int p1, int p2=p1); //This does not work though I wish it would :( 

error: local variable ‘p1’ may not appear in this context;


How do I get my function to set the 2nd parameter to the 1st parameter if a 2nd parameter was not typed in?!?!?!

Does the second parameter need to take all possible integer value? Or can you set one "special value" away for this purpose?

Where use_default is a const in set to a "special value".

1
2
3
4
5
6
void Not_A_Good_Function(int p1, int p2=use_default)
{
    if(p2==use_default)
        p2=p1;

    ...



Oops! - we are talking about C++ !! See sloppy9's solution.

(My solution might be of use if C ever gets default params...)
Last edited on
closed account (DSLq5Di1)
Overloading the function may be a viable alternative,

1
2
3
4
5
6
7
8
9
void Function(int p1, int p2)
{
    // ...
}

void Function(int p1)
{
    Function(p1, p1);
}

@andywestken
although that's the first thing I considered too, it seems like an awfully dangerous and misleading thing to do :\

@sloppy9
oh good thinking, I suppose that's pretty much the best thing i can do.
Thanks :)
Remember to make the one function inline if applicable and/or if the compiler isn't doing it anyway.

EDIT: So put it in a header file rather than a source file.
Last edited on
@Xander314
I understand the inlining, but why must it be in a header file?
It doesn't need to be in a header file.

But the whole function must be seen by the compiler before it's used.

So if you're just using it in one cpp file, it can be defined higher up in the same file. But -- as cpp file shouldn't be including other cpp files -- if you want to use the same function in more than one cpp file, it needs to go in a header [1].

Andy

[1] There's nothing to actually stop you cutting and pasting the identical function into loads of cpp files. This would work. But if you find an error in one occcurence, you'd have to go and edit all the others ones, too.
Last edited on
Header file
1
2
3
4
5
6
void Function(int p1, int p2);

inline void Function(int p1)
{
    Function(p1, p1);
}

CPP file
1
2
3
4
void Function(int p1, int p2)
{
    // ...
}

This tells the compiler that it can magically make all instances of the one-argument Function actually disappear from your executable (this is a good thing!) while giving you the convenience to pretend that there are actually two functions...

1
2
Function(12);    // this is really compiled as: Function(12,12)
Function(19,-7);

Hope this helps.
3 cheers for optimization! good to know! :)
Topic archived. No new replies allowed.