c++c++11default-argumentsfunction-signature

What is the use case for default argument without name in the function signature


Taken from cpp reference, https://en.cppreference.com/w/cpp/language/default_arguments

void f(int, int = 7); // #2 OK: adds a default

Is there any particular use case where this is useful, considering there is no name to the default argument.

Or I am just reading too much between the lines and should just leave with the understanding that it is just the function signature declaration and in function definition one has to provide the variable name to make any use of the second parameter in the function.

I was expecting the variable name in the function signature.


Solution

  • void f(int, int); is a function declaration, which is different of function definition.

    In the declaration, we (the compiler) only need to know that we declare a function f that takes 2 ints and returns a void.

    The names of the parameters are not necessary here since we do not refer to them.

    But in the definition, it's another story. In that case, we need to specify parameters names in order to be able to use them.

    For example:

    // Declaration
    void f(int, int);
    
    // Definition
    void f(int a, int b)
    {
        std::cout << a << ',' << b << '\n';
    }
    

    In the above example, we could not use the a and b in the function definition if we did not give them those names. But in the declaration, we didn't care.

    Note: It may still be useful to specify names in the declaration for documentation purposes (or simply to help the human reader).

    Note 2: Actually you can also omit the parameter name in the definition, but in that case, you won't be able to refer to it.
    It is sometimes used when we plan to define the function body later and do not want to have a "unused parameter" warning while compiling (Although I personally prefer to keep and comment out the parameter name instead).