Function parameters in an if statement

Oct 14, 2015 at 6:45pm
Hi, is there a way to execute a line of code if the function is provided with 2 parameters and another line of code if it's provided with only 1 instead? Let's say I have this function:

1
2
3
4
5
6
7
8
9
10
11
12
int blah(const char* prompt, int y = 0)
{
    std::cout << prompt << std::endl;
    if (y is provided)
    {
        do something with y;
    }
    if (y is not provided)
    {
        do another thing in general;
    }
}


If in main() I call blah("The prompt", 5);, I want it to execute the if (y is provided) code, if I call blah("The prompt"); I want it to execute the if (y is not provided) code. What should be next to if? Thanks!
Oct 14, 2015 at 7:13pm
This is what function overloading is for. Create two versions of the function: one with two required parameters and one with one required parameter. Default parameters are only useful when your code is the same in both cases.
Last edited on Oct 14, 2015 at 7:14pm
Oct 14, 2015 at 7:28pm
Thank you, that is what I was looking for. I'll go figure out how to use it properly now.
Topic archived. No new replies allowed.