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

StackOverflow https://stackoverflow.com/questions/20785789

  •  21-09-2022
  •  | 
  •  

Question

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));
               ^  
Was it helpful?

Solution 2

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;
}

OTHER TIPS

You need to provide a forward declaration for fact

long int fact(int n);
int main(){
    // body
}
long int fact(int n) {
    // body
}    

Without this, ansii C assumes a function without a prior declaration or implementation will return int

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top