Search code examples
c++functionoptional-parametersoptional-arguments

Is there a way to explicitly call optional arguments in c++?


When I create a function such as:

int addThree(int x=1, int y=1, int z=1)

I want to call the function such that it uses the default arguments for x and z, but not y.

Some attempts have been addThree(5,,5) and addThree(5,NULL,5), but neither work effectively.


Solution

  • The default arguments must be at the last of your list, so do as follows

    int addThree(int y , int x = 1, int z = 1)
    {
        //some stuff
        return someInt;
    }
    

    , hence you can call it as

    int ans = addThree(4);