Search code examples
c++parametersdefault

default parameters without name in c ++


Consider the functions:

void foo(int a = 3)//named default parameter
void foo1(int = 3)//unnamed default parameter

I understand the need of the first function.(The value of "a" is 3 and it can be used in the program). But the 2nd function(which is not an error) has 3 initialized to nothing. How exactly do i use this value , if i can use this value...


Solution

  • In function declaration/definition, a parameter may have or have not a name, this also applies to a parameter with default value.

    But to use a parameter inside a function, a name must be provided.

    Normally when declare a function with default parameter

    // Unnamed default parameter. 
    void foo1(int = 3);
    

    In function definition

    void foo1(int a)
    {
       std::cout << a << std::endl;
    }
    

    Then you can call

    foo1();   // the same as call foo1(3)
    foo1(2);