Home > Software design >  What actually is "conflicting type"?
What actually is "conflicting type"?

Time:09-18

#include<stdio.h>
long fact(int x);

int main()
{   long x=fact(5);
    printf("%ld",x);
}

long fact(long x)
{
    long prod=1;
    int i=1;
    if(x==0)
        return 1;
    else
    {
        while(i<=x)
        {
        prod=prod*i;
        i  ;
        }
    return prod;
    }

}

Here's the code I am using to find out the value of e (to the power x,here x=1) e^x series

Now I get the following ERROR:

error: conflicting types for 'fact' I am using long return type all the time

EDIT: I changed the definition signature and it worked:

#include<stdio.h>

long fact(int x)
{
    long prod=1;
    int i=1;
    if(x==0)
        return 1;
    else
    {
        while(i<=x)
        {
        prod=prod*i;
        i  ;
        }
    return prod;
    }

}

int main()
{   long x=fact(7);
    printf("%ld",x);
}


CodePudding user response:

Your declaration long fact(int x); and definition long fact(long x) ... don't agree on type of the argument x. Here is a more streamlined version:

#include <stdio.h>

long fact(int x) {
    long prod = 1;
    for(int i = 2; i <= x; i  )
        prod *= i;
    return prod;
}

int main() {
    long x = fact(7);
    printf("%ld", x);
}

As factorial grows so fast I suggest adding an assert or error check that x <= 21 if long is 8 bytes (22! > 2^64-1). Factorial is usually defined for non-negative numbers so consider using unsigned types: unsigned long for the return type, and maybe even unsigned char x for the argument.

  • Related