Home > Net >  How can i set a default value for a missing argument inside void statement C
How can i set a default value for a missing argument inside void statement C

Time:12-28

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?

CodePudding user response:

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.

CodePudding user response:

What you want is known as a default argument where you assign the value to the parameter in the function declaration or definition if you do not have a forward declaration for the function. In the below example the default argument for aValue2 is set to 100.

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