Default Arguments C++: Look at them Closely

We all know what are Default Arguments C++ are, but while playing with them,

I found 2 interesting things, many of you might know this but this will be new for freshers and learners.

 

1-) Look at the following code closely:
#include <iostream>

// something looks missing
void init(int =1, int =2, int =3);

int main()
{
    init();
    return 0;
}

void init(int a, int b, int c)
{
    std::cout << a << ' ' << b << ' ' << c;
}

 

If you closely observe function prototype then it looks like an error but it isn’t actually.
Variable names can be omitted in default arguments.
2-) Predict output of the following Code:
#include <iostream>
void init(int a=1, int b=2, int c=3);

int main()
{
    init();
    return 0;
}
void init(int a=1, int b=2, int c=3)
{
    std::cout << a << ' ' << b << ' ' << c;
}

 

The above program looks correct at first glance but will fail in compilation. If function uses default arguments then default arguments can’t be written in both function declaration & definition. It should only be in declaration, not in definition.

Correct version is:
#include <iostream>
void init(int a=1, int b=2, int c=3);
int main()
{
    init(); // It is fine
    return 0;
}
void init(int a,int b,int c)
{
    std::cout << a << ' ' << b << ' ' << c;
}

 

If you find this information useful share it!! or if anything incorrect then comment down.

Leave a Comment