I'm having issues with optional parameters
on recursive functions
Here is a sample code:
private static void RecursiveFunction(int x, int optional = 0)
{
if (x < 5)
RecursiveFunction(x + 1, optional++);
}
When invoking the function:
RecursiveFunction(0);
I've got the following results (just calling this code string.Format("{0} - {1}", x, optional)
in the immediate window):
"0 - 0"
"1 - 0"
"2 - 0"
"3 - 0"
"4 - 0"
Am I missing anything here? Thanks!
Change from:
RecursiveFunction(x + 1, optional++);
// ^^
To:
RecursiveFunction(x + 1, ++optional);
// ^^
The first one does the action then increments optional
.
The second one does the action after it increments optional
.
From MSDN:
++ var
var ++
The first form is a prefix increment operation. The result of the operation is the value of the operand after it has been incremented.
The second form is a postfix increment operation. The result of the operation is the value of the operand before it has been incremented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With