Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Co-routine

Name: Anonymous 2012-01-23 17:40

Is this iterator implementation well-defined?


#include <stdio.h>
#include <stdlib.h>

typedef struct it {
    int *start;
    int len;
    struct it *next;
} iterator_t;

static iterator_t *head = NULL;

static iterator_t *iterator(int array[], int length)
{
    static iterator_t *ptr = NULL;

    if (head == NULL) {
        head = malloc(sizeof(iterator_t));
        ptr = head;
    } else {
        ptr->next = malloc(sizeof(iterator_t));
        ptr = ptr->next;
    }

    ptr->start = array;
    ptr->len = length;
    ptr->next = NULL;

    return ptr;
}

static int iterate(iterator_t *it)
{
    static iterator_t *current = NULL;
    static int state = 0, *ptr;

    if (it != NULL) {
        /* Initialize */
        current = it;
        ptr = it->start;
        state = 0;
    } else {
        /* Co-routine */
        switch (state) {
            case 0: while (ptr != (current->start + current->len)) {
                        state = 1;
                        return *ptr;
                       
                        case 1: ++ptr;
                    }
        }
    }

    return -1;
}

int main(void)
{
    iterator_t *it, *ptr;
    int n, numbers[] = { 4, 5, 6, 0, 1, 9, 0, 0, 8 };

    it = iterator(numbers, sizeof(numbers)/sizeof(int));

    iterate(it);
    while ((n = iterate(NULL)) != -1) {
        printf("%d\n", n);
    }

    it = head;
    while (it) {
        ptr = it->next;
        free(it);
        it = ptr;
    }
    return 0;
}

Name: Anonymous 2012-01-23 20:03

>>34
I know this might be hard for some of you mental midgets to grasp, but you can sort of tell who is who based on their writing style.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List