[ILUG-BOM] A C factorial Problem

q u a s i quasiabhi@[EMAIL-PROTECTED]
Thu Dec 26 12:47:39 IST 2002


Abhijeet D Mhatre <abhijeetmhatre at hotpop.com> writes:

> ****************************************
> * LUG meet on 12 Jan. 2003 @ VJTI
> ****************************************
> 
> HI friends 
> I was experimenting with a common c factorial problem
> when I got a totally unexpected result.
> 
> here is the program
> 
> # include <stdio.h>
> main(){
>    int fact;
>    int x;
>    fact=factorial(6);
>    printf ("%i\n",fff());
> }
> 
> 
> int factorial(int x){
>    if(x>1) return(x*factorial(x-1));
> }
> 
> int fff () {
>    ;
> }
> 
> 
> Naturally I was expecting  1 as the answer. But I am getting the answer 720 
> which is 6!.

The function fff() is supposed to return an integer according to definition.  But it does not.  The return of the previous function which is on the stack is taken instead.  If you insert a 'return int;' then the value of int is printed.

A good experiment anyway.  This is the reason why I love C and so many hate it. '-)

> 
> If I comment the 5th line fact=factorial(6); I am getting the expected result 
> "1".

But I am wondering why it should print "1"...  & why is it expected.


quasi





More information about the Linuxers mailing list