Why am I getting an initialization from incompatible pointer type warning?

15,287

In C a function (or it's prototype) should be declared before it is used in order to determine the correct signature of it. Otherwise the compiler will try to "guess" the correct signature. While it can infer the parameter types from the call, it is not the case with return value type, which is defaulting to int. In your code the function wasn't prototyped prior the usage, so the compiler is assuming it is returning int. This is the reason it is warning you about incompatible type assignment.

Share:
15,287
user163911
Author by

user163911

Updated on June 04, 2022

Comments

  • user163911
    user163911 almost 2 years

    So I'm using gcc on Linux and have the following two code snippets in separate files (only relaveant sections of code included):

    int main()
    {
        /* Code removed */
        int_pair_list *decomp = prime_decomp(N);
        if (decomp)
            while(decomp->next)
                decomp = decomp->next;
        printf("%d\n" decomp->value_0);
    }
    

    int_pair_list *prime_decomp(unsigned int n)
    {
        int_pair_list *head = malloc(sizeof(*head));
        int_pair_list *current;
        /* method body removed, current and head remain as int_pair_list pointers */
        return current ? head : NULL;
    }
    

    The program compiles and runs correctly but, during compilation, I get the warning:

    problem_003.c: In function ‘main’:
    problem_003.c:7:26: warning: initialization from incompatible pointer type [enabled by default]
      int_pair_list *decomp = prime_decomp(N);
                          ^
    

    I'm new to C and I just can't work out why I'm getting this warning.