Kayla
Kayla

Reputation: 11

C Recursion program won't compile w/ GCC

#include <stdio.h>

int main (void)

{
int n, x;

int factorial (int n)
{
if (x<=0)
{
 printf("x equals: ");
return 1;
}
else
{
return n * factorial (n-1); 
}
f(x)=f(x-1)+2; //says error is here
}
return 0;
}

I've tried some things and can't get it to work. I could just be overtired and looking past the smallest thing but help would be much appreciated! Thanks :)

Upvotes: 1

Views: 221

Answers (3)

Jason
Jason

Reputation: 32530

You cannot declare a function definition inside of main() or any other function ... function definitions have to be stand-alone and cannot have embedded function definitions inside of them.

Also I'm not sure what you're doing on the line that you've marked as an error since f() is not a defined function, so you can't call it. Furthermore, it would need to return some type of l-value, such as a pointer to a static variable declared inside the function, or a pointer passed by reference to the function and even then the syntax is not right since there would be a required dereference ... so basically you can't do what you're doing on that line.

To get something that compiles, try

#include <stdio.h>

int factorial (int n)
{
    if (n <= 0)
    {
        return 1;
    }
    else
    {
        return n * factorial (n-1); 
    }
}

int main (void)
{
    int x;

    x = factorial(5);
    printf("Factorial of 5 is equal to %d", x);

    return 0;
}

Upvotes: 6

Prasoon Saurav
Prasoon Saurav

Reputation: 92874

A function cannot be defined inside another function. However gcc allows it as an extension. You have defined a function named factorial but are trying to use f which hasn't been declared anywhere.

Upvotes: 1

dwerner
dwerner

Reputation: 6602

Use indentation to see possible problems with scope:

 #include <stdio.h>

int main (void)
{
    int n, x;

int factorial (int n)
{
    if (x<=0)
    {
        printf("x equals: ");
        return 1;
    }
    else
    {
        return n * factorial (n-1); 
    }
    f(x)=f(x-1)+2; //says error is here
}
return 0;

}

As far as I can remember, C doesn't have closures.

Upvotes: 1

Related Questions