-1

Normally, I must use "else return 1". However, it works without that line. Thanks for answers.

#include<stdio.h>
    int f(int x)
    {
          if(x!=1)
          return x*f(x-1);

          //else return 1

    }
    int main()
    {
      int x;scanf("%d",&x);
        printf("%d",f(x));
    }
HzAli
  • 1
  • 1

1 Answers1

1

Well that's undefined behavior. The return value holds no meaning as far as the factorial is concerned. In fact factorial of 1 is 1 not 3 so it is giving an incorrect result. There is no meaning whatsoever. Even if it gave you correct result - on this case 1 don't think that this is somehow a correct code and will work no matter what. It won't.

Also the compiler mentioned about this when you complied with all flags enabled. gcc -Wall -Werror progname.c.

To explain undefined behavior:-

The standard explicitly chooses to not define how a compiler should behave if it encounters Undefined Behavior. As a result, a compiler is free to do whatever it sees fit and may produce useful results, unexpected results, or even crash. You shouldn't rely on that.

user2736738
  • 30,591
  • 5
  • 42
  • 56