I'm sure this has been asked hundred of times before, but curiously I can't find anything... I wonder how I can reassign a value to a default function parameter upon call specifically, omitting other parameters that stand to the left of it.
This does not compile, as I was used from python. But how to do it?
void test(int i=0, int j=1){
std::cout << i << " " << j << std::endl;
}
int main()
{
test(j=2);
}
Ok, it's not possible. Let me rephrase my question then. WHY is it not possible?
Now, your question is why it's not allowed rather than if it is allowed. Knowing that you come from Python, the answer is easier to explain.
In Python, an assignment is an statement, but not an expression. That means that you cannot assign a value to a variable in, for example, a function call:
>>> def foo(bar):
... return bar
...
>>> x=0
>>> foo(x=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'x'
Meanwhile, in C++, an assignment is an expression, and not an statement. Thus, something like this is allowed:
void foo(int x) {
// ...
}
void oof() {
int x = 0;
foo(x = 1);
}
In this situation, 1
is assigned to x
, and the new value of x
is passed on as an argument to foo()
. All this clutter comes from a man named Bjarne Stroustrup, who for no one's good decided to preserve (some) compatibility with the inventions of another man, namely Dennis MacAlistair Ritchie.
Now, it's pretty obvious to understand why allowing keyword parameters in C++ would involve unresolvable stack overflows (but of the compiler, not of your program...). How would the program differentiate between a traditional assign-and-return
expression as described above, and a keyword parameter? It's simply impossible to do so without modifying the language to the point it's no longer even part of the C family.
This mess is (somewhat) resolved by the fact that Python didn't wanted compatibility with C/C++/C--/~C/!C/*C/&C/..., but it did wanted to allow keyword parameters, and thus another man, namely Guido van Rossum, decided to make assignments statements, as they have always needed to be. This allowed for the syntax used above in C++ to be available in Python for keyword arguments.
Ah! And, if you have any ideas to make C++ even more complex, why not go and say the first thing that comes to your mind to ISO/ETC JTC1, SC22, WG21? I'm sure they'll standarize it, whatever it is, and you'll be spyied for the rest of your life by the some gnomes fabricated in Redmond.