0

Recursion - Return 1 versus Return Variable

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { static int Fact(int num) { if (num == 1) { return 1; } return num * Fact(num - 1); } static void Main(string[] args) { Console.WriteLine(Fact(6)); } } } I understand that return 1; is the exit for the recursion. static int Fact(int num) { if (num == 1) { return 1; I don't understand how using 1 returns the value of num to the caller. Wouldn't it make more sense to return num explicitly like below? static int Fact(int num) { if (num == 1) { return num;

27th Apr 2017, 9:51 PM
Shane Ferrell
2 ответов
+ 1
Since the if statement checks to see if num equals 1 then returning num or returning 1 are equivalent, it doesn't matter which one you use. There may possibly be some efficiencies gained by using a constant (1) rather than a variable (num) but suspect it wouldn't be noticeable.
27th Apr 2017, 9:59 PM
Shane
+ 1
Another advantage over 1 is that if for whatever reasons you need to change the variable's name you'd only need to change it once. "Syntax efficiency"
27th Apr 2017, 10:07 PM
Bebida Roja
Bebida Roja - avatar