Reputation: 3125
I have a problem while compiling this code on gcc 4.7.2 (Ubuntu Server 12.10)
#include <stdio.h>
int main()
{
long int facto = 30;
printf("%ld\n", fact(facto, facto - 1);
}
long int fact(long int n, long int a)
{
if (a == 1)
return (n);
fact(n * a, a - 1);
}
I know this can be done with a one argument function but it's not the point here.
The error I got is : conflicting type for 'fact' (line of function declaration) previous implicit declaration of fact here (line with printf)
Upvotes: 0
Views: 400
Reputation: 42175
You need a forward declaration for fact
before you call it from main
long int fact(long int n, long int a); // forward declaration
int main()
{
long int facto = 30;
printf("%ld\n", fact(facto, facto - 1);
}
long int fact(long int n, long int a) // actual function
You could just move the implementation of fact
above main
in this case. Note however that this approach won't scale to more complex programs with more longer functions calling into each other.
ADD Your factorial function is wrong. Here is the corrected version
long int fact(long int n)
{
if (a == 1)
return (n);
return n * fact(n - 1);
}
Upvotes: 6
Reputation:
#include <stdio.h>
long int fact(long int n, long int a);
int main()
{
long int facto = 30;
printf("%ld\n", fact(facto, facto - 1);
}
long int fact(long int n, long int a)
{
if (a == 1)
return (n);
fact(n * a, a - 1);
}
You need a function prototype, which is basically the first line of the function with a semicolon. This will tell the compiler that this function exists.
Upvotes: 0