r/ProgrammerTIL • u/starg2 • Aug 01 '20
C++ [C++] TIL that default arguments can be added to a function that was already declared
https://en.cppreference.com/w/cpp/language/default_arguments
Example:
#include <iostream>
int add(int a, int b) // function definition with no default arguments
{
return a + b;
}
int add(int a, int b = 3); // adds a default argument
int add(int a = 2, int b); // adds another one
int main()
{
std::cout << add() << std::endl; // calls add(2, 3)
return 0;
}
139
Upvotes
64
u/SomeRandomScientist Aug 01 '20
Doesn't matter how much you think you know about C++, there's always more.
89
u/SurDin Aug 01 '20
Please don't use this.
25
u/lithium Aug 01 '20
If you do this you're fired.
8
u/Romenhurst Aug 01 '20 edited Aug 01 '20
So which default argument would
add(1)use?I never knew you could provide default values for arguments before the required argument.
Are those declarations exactly the same thing as just writing
int add(int a = 2, int b = 3);?6
u/Play4u Aug 01 '20
Yup, you should only take care that you do not define the same default argument in both the function's declaration and definition.
Only one or the other (preferably the declaration)
6
u/tending Aug 01 '20
Someone tell me how we can abuse this for template metaprogramming.
1
u/AboutHelpTools3 Aug 31 '20
C++ is so full of surprises, amazing.
I don't think I will ever use this.
1
u/MacASM Nov 03 '20
jeez, C++ is too full of surprises. I would rather use D just due to not having many of those things, if compared to C++.
1
u/IAMKING77 Nov 30 '20
How would u incorporate this into a social website platform?
-3
u/chicksOut Aug 01 '20
I'm seeing a lot of mixed responses, I'll try to provide as objective a response as i can. Default arguments is a tool we utilize quite regularly in our codebase. It's very helpful for functions with 1 widely used use case, that still has variable corner cases. This paradigm allows the function to be called with minimal parameter inputs in most cases, while still allowing for the more variable use cases to have that dynamic ability. My personal opinion, as is most things with c++, it can be a valuable tool, or it can be an abused red headed stepchild, it all depends on use, and implementation and using the right tool for the job.
-13
u/its_the_other_guy Aug 01 '20
You can also do the same in almost any logic.
For example: If (x = 5) {...}