This defaults to user input if the arguments are not passed at compile time.. How effective is this technique and where can it be applied?

#include <iostream>

void foo(unsigned number = []() {unsigned num = 0; std::cin >> num; return num; } ()) {
    std::cout << number << "\n";

int main() {
    foo(1); //prints 1
    foo();  //defaults to user input    
    return 0;
  • \$\begingroup\$ There's a problem with your main function parameter definition,, fix that please. \$\endgroup\$ – πάντα ῥεῖ May 21 '20 at 15:50
  • \$\begingroup\$ I do not see much benefit of this other than code being closer to the call site. Perhaps you could create more complex and concrete example that would better illustrate the advantages? \$\endgroup\$ – Incomputable May 21 '20 at 18:12
  • \$\begingroup\$ That's what I am asking for XD. Can you think of any? \$\endgroup\$ – d4rk4ng31 May 21 '20 at 18:13
  • \$\begingroup\$ This does not look actual code from one of your projects. \$\endgroup\$ – greybeard May 21 '20 at 20:45
  • \$\begingroup\$ @greybeard, It isn't and I'm really sorry for that. But I wanted to know the implications of the code if I use it in my project. I know I've violated the guideline and should be 'fined' for that. I will be fine with it, even if you vote to close this question (which I guess you probably have). P.S. I will refrain from such questions in the future :) \$\endgroup\$ – d4rk4ng31 May 21 '20 at 21:05

I haven't seen this pattern in use, and I wouldn't use it personally, for two reasons:

1) Unintuitive - Changing the function's behavior in this significant of a way is not something you'd expect from the default value of a parameter.

2) Mixing Concerns - It's almost always better to separate your I/O from your algorithm.

Considering that this is a compile-time difference anyway, it would be more clear to have another method to read input. For example:

  • \$\begingroup\$ Please don't take the code literally. I wanted to focus on the part wherein default arguments are user input. The definition may be different. \$\endgroup\$ – d4rk4ng31 May 21 '20 at 18:55
  • \$\begingroup\$ Gotcha. In that case, point 2 applies even more-so. \$\endgroup\$ – Errorsatz May 21 '20 at 18:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.