function with predefined value

Hi

I'd like create a function ex: function(int value1, int value2, int value3=1).
That is if you just call the function with two arguments ex: function(1,2) the last value (value3) should be set to 1. But if you call it with three, value3 should be set to the one you choose. Is there a way to do that?

Thanks
/Christian
Last edited on
Can not call the function with just two arguments, if you promised for 3. It will cause an error.
@ chria
the example you gave works perfectly as you want
eg:
1
2
3
4
5
6
7
8
9
10
11
void function(int value1, int value2, int value3=1)
{
    //...
}

int main()
{
    function(1,2); // value3 is equal to 1
    function(1,2,3);
    return 0;
}


Notice that when forward declaring the function you should define the default values only once:
1
2
3
4
5
6
7
8
9
10
11
12
13
void function(int value1, int value2, int value3=1);

int main()
{
    function(1,2); // value3 is equal to 1
    function(1,2,3);
    return 0;
}

void function(int value1, int value2, int value3) // already defined default arguments
{
    //...
}
Last edited on
You also get an error for tring this
1
2
3
// prototype witch has an error
int function(int value1 = 2, int value2, int value3 = 3);

Because you only can have default values starting at the right side of the function

Example:
if value3 has a default value, so can value2.
if value3 and value2 have default values so can value1.
Thanks! What I did wrong then was to define the value in my .cpp file instead of my .h file. Thanks again
Topic archived. No new replies allowed.