Search code examples
c++void

How can i set a default value for a missing argument inside void statement C++


So, I have this code for example:

void doSomething(int aValue, int aValue2) {
    /*thigs to do...*/
}
int main() {
    doSomething(9);
}

Notice that I only used 9 for aValue and had aValue2 empty.

What I want is to automatically fill-in the missing aValue2 with a certain default value.

Is there any way to do that?


Solution

  • There are at least two ways to do it. The first way is to declare your function with a default-argument, like this:

    void doSomething(int aValue, int aValue2 = 123);
    

    ... then when it is called with only one argument, the compiler will treat the call as if the second argument was supplied as 123. Note that the default value goes in the line where the function is declared, not where it is defined, so in cases where you have a separate .h file containing the function's declaration, the = 123 would go there and not in the .cpp file.

    The other way would be to overload the function, like this:

     void doSomething(int aValue, int aValue2) {
         /*things to do...*/
     }
    
     void doSomething(int aValue) { 
         doSomething(aValue, 123);
     }
    

    This is a little wordier, but it gives you more flexibility in deciding how the first (two-argument) version of the function should be called when the caller supplies only one argument.