Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Recursive Function with Optional Parameter

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!

like image 374
KaeL Avatar asked Dec 04 '22 13:12

KaeL


1 Answers

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.

like image 197
gdoron is supporting Monica Avatar answered Dec 18 '22 06:12

gdoron is supporting Monica