0

The following is a simple code getting a factorial of a number. I have noticed it works with or without the return at the end of my function block ("return number"). Is there any differences to use it or not, and if not then what is the standard practice?

# include <iostream>

int factorial(int number){
    if (number == 1){
    return 1;
}
else {
    number = number * factorial (number -1);}
    return number;
}

int main(){
std:cout << "Enter your number: ";
int number; std::cin >> number;
std::cout << "\n" << factorial (number) << "\n";
}
  • 3
    A function that is declared to return anything other than `void` *must* always `return` something fitting the return type or you have [Undefined Behaviour](https://en.cppreference.com/w/cpp/language/ub). `main` is special and the only exception to the rule though. – Jesper Juhl Sep 12 '20 at 18:06
  • 2
    Except for the function main() – JVApen Sep 12 '20 at 18:06
  • Yes return is required, you've just learned a valuable lesson however. One which most newbies don't learn for a long time. The lesson is that sometimes, incorrect programs work. Worth remembering. – john Sep 12 '20 at 18:10

0 Answers0