Default value in functions

If I create a function with default value inputs like this prototype:
void F(int a = 0, int b = 1, int c = 2);
And I want to call this function with default value only for second variable something like this:
F(2, , 3);
means i want to pass 2 for the first, 3 for the third variable but i want the second one to get the default value.
How can i do this?
Unfortunately, you can't do this -> F(2, ,3);

A simple solution would be to pick a value outside the domain
of your function and use this to indicate a default parameter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int F(int a = 0, int b = 1, int c = 2)
{
    if (a == -1) a = 0;
    if (b == -1) b = 1;
    if (c == -1) c = 2;

    return a * b * c + a + b + c;
}

int main()
{
    std::cout << F()         << std::endl; // F( , , )
    std::cout << F(1,2)      << std::endl; // F(1,2, )
    std::cout << F(1, -1, 3) << std::endl; // F(1, ,3)
    std::cout << F(-1, 2, 3) << std::endl; // F( ,2,3)

    return 0;
}

If you want it to be trickier, you can do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

class area
{
    double width_;
    double height_;

public:

    //default values
    area(): width_(5.0), height_(5.0) {}

    area & width (double w) { width_  = w; return *this; }
    area & height(double h) { height_ = h; return *this; }

    double operator()()
    {
        return width_ * height_;
    }
};

int main()
{
    std::cout << area()                         () << std::endl;
    std::cout << area() .width(10)              () << std::endl;
    std::cout << area()             .height(15) () << std::endl;
    std::cout << area() .width(2.5) .height(4)  () << std::endl;

    return 0;
}

Also, check these out:

http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.20
http://www.boost.org/doc/libs/1_47_0/libs/parameter/doc/html/index.html
Topic archived. No new replies allowed.