Search code examples
crecursionfactorial

error message "format ‘%ld’ expects argument of type ‘long int’, but argument 2 has type ‘int’"


I am writing a simple program to find the factorials for the first 'n' integers. But there is this error that i am encountering when compiling it. Even thought the return type of fact() function is long int, the error still persists.

#include <stdio.h>
#include <stdlib.h>

int main(){
    int i;
    for(i=0;i<30;i++)
        printf("%ld\n", fact(i));
    return 0;
}

long int fact(int n){
    if(n==0)
        return 1;
    else 
        return (long)(n*fact(n-1));
}

Error:

fourth.c:7:3: warning: format ‘%ld’ expects argument of type ‘long int’, but argument 2 has type ‘int’ [-Wformat=]
printf("%ld\n", fact(i));
^
fourth.c: At top level:
fourth.c:11:10: error: conflicting types for ‘fact’
long int fact(int n){
         ^
fourth.c:7:19: note: previous implicit declaration of ‘fact’ was here
printf("%ld\n", fact(i));
               ^  

Solution

  • You forgot to include function prototype before main. Either include a prototype

    long int fact(int n);
    

    or move your function definition before main.

    #include <stdio.h>
    #include <stdlib.h>
    
    long int fact(int n){
        if(n==0)
            return 1;
        else
            return (n*fact(n-1));
    }
    
    int main(){
        int i;
        for(i=0;i<30;i++)
            printf("%ld\n", fact(i));
        return 0;
    }