Scenario:
Let’s say for example, I have two functions.
First function is concerned with reading a single bit, thus returing true or false.
Second function is concerned with reading a variable number of bits using first functions n times where n is the number if bits.
First Function:
private bool ReadBit ( )
{
.
.
.
}
Second Function: ( Recursive is using here instead of loop iteration well-known techniques )
public List<bool> ReadBits ( int Value ) //Value = Number of Bits
{
List<bool> Result = new List<bool> ( );
if ( Value == 0 )
{
return Result;
}
else
{
Result . Add ( ReadBit ( ) );
return ReadBits ( --Value ); //OPTION 1
ReadBits ( --Value ); //OPTION 2
}
}
I Know OPTION 2 will throw an error about “not all code paths return a value“.
This is not the problem as I can deceive the compiler many ways !
My Question:
What are the real deference between OPTION 1 & OPTION 2 ?
I swear both will do the recursive concept if we add a return line somewhere with OPTION 2 & re-order lines somewhat.
The difference is this:
Of course, you want neither. You want to return the correct result:
That is, you first add the currently read bit, and then append all the next read bits (that were created recursively).
However, this is wildly inefficient. It’s much more efficient to reverse the process, thus creating only a single list.
But note that this will of course reverse the order of your result list.
Much as I like recursion, why not go with the iterative approach here that can be expressed much more naturally in C#?