A self-referential structure is a data structure that includes references to other data of its same type. A simple example of this would be an implementation in C of a linked list:

           typedef struct listnode {
               void *data;
               struct listnode *next;
           } list_t;

The reference to a listnode struct from within a listnode struct is the self-referential aspect of the structure.

Self-Referential Structures are one of the most useful features that I can think of in a programming language such as C. They allow you to create data structures that contain references to data of the same type as themselves.

They are also designed to make people who are just learning how to program cry, alot. From these people you get questions such as "how can a struct of type foo contain a reference to a variable of type foo in its own delcaration"? The correct answer to this is "because it can".

They also allow you to do interesting things with functions that call themselves, although this can be done without self-referential structures they tend to be more usefull with them.

For a simple example let's look at some code for a linked list of ints

typedef struct linklist
    int data;
    struct linklist *next;
} linklist;

Although this makes perfect sense to anyone who does alot of coding, it will almost always make a newbie coder look at it in horor. But maybe not as much horor as the following...

This is a very simple function that searches through a linked list using the struct above and returning true if the number is in the list, otherwise false.

int list_search(int search, linklist *list)
    int ans;

    if(list == NULL)
        ans = 0;
        if(search == list->data)
            ans = 1;
            ans = list_search(search, list->next);

    return ans;

This will make people cry as they try to work out how an answer appears from a deep nested structure.

But both of these are great fun once you wrap your head around them. Until that point they are Hell.

Log in or registerto write something here or to contact authors.