Hello! I understand the essence of this algorithm, but I can not figure out why if you remove the return in front of x in the recursive function, then the answer becomes incorrect. How does return work in this example, and why not do without it?

 #include <iostream> int fact(int x) { if (x == 1) return 1; return x * fact(x - 1); } int main() { std::cout << fact(5) << std::endl; system("pause"); return 0; } 
  • 3
    Why do I need return in this programming language? - Igor

1 answer 1

Let's remove return before x :

 int fact(int x) { if (x == 1) return 1; x * fact(x - 1); } 

What is happening here:

  • At the beginning of the function, the function parameter x is checked for equality to one.
  • In the case of equality returns one, since 1! = 1 1! = 1
  • In case of inequality, the line x * fact(x - 1); is executed x * fact(x - 1);

    • This line calculates the product of x and the result of the recursive function call
    • Since we have removed the return , it is not returned, it is just calculated and the function continues to be executed.
    • The code reaches the end of the function.
    • Since no return was executed, some garbage will be returned from the function.
    • You can catch such errors at compile time by adding the -Wall flag. For example, when I compile with this flag, the following warnings appear:

       % g++ -Wall main.cpp main.cpp: В функции «int fact(int)»: main.cpp:6:7: предупреждение: вычисленное значение не используется [-Wunused-value] x * fact(x - 1); ~~^~~~~~~~~~~~~ main.cpp:7:1: предупреждение: управление достигает конца не-void функции [-Wreturn-type] } ^ 
  • one
    Thank you very much, you helped me a lot) - Wis Pinger
  • UB will, that's what happens. - Abyx
  • @Abyx, yes, it was better to write about UB than about everything else ... It's sad. - diraria
  • one
    @Abyx: true: "this is the case in a value-returning function." n2356 (c ++ 98) §6.6.3.2 - jfs