Matan
Matan

Reputation: 43

C: Incomplete return type

I tried to implement linked list in C, and started with this simple code:

#include <stdio.h>

struct int_node;
struct int_list;
struct int_list create_list();

int main() {

    struct int_list list = create_list();
    return 0;
}

struct int_node {
    int value;
    struct int_node * next;
};

struct int_list {
    struct int_node * first;
};

struct int_list create_list() {
    /* Creates an empty list, first node=null */
    struct int_list list;
    list.first = NULL;
    return list;
};

While building I got two errors:

  1. Calling 'create_list' with incomplete return type 'struct int_list'
  2. Variable has incomplete type 'struct int_list'

I looked for an answer and all I could find was that I need to declare the structs and the functions before I use them, which I did.

Another thing I tried was to move the main() function to the end, and that solved the errors, but it's a silly workaround and I want to find out the real solution.

Any help?

Upvotes: 3

Views: 5990

Answers (2)

Spaceman Spiff
Spaceman Spiff

Reputation: 934

Actually you need to define the structs before you use them, or else how does the compiler know what a struct int_node is when it sees it in the main method. So as Bill Lynch said your simple fix is actually just the correct way.

You should look in to how exactly a program goes from source code to an executable in C if you are interested in learning more. Here is an interesting and not to long page about it.

Upvotes: 1

Bill Lynch
Bill Lynch

Reputation: 82006

The definitions of the structs should also be placed before main(). That is, your silly fix is actually the correct fix.

Upvotes: 6

Related Questions