maximusg
maximusg

Reputation: 143

C programming Linked list for loop

Given the standard linked list where "apples" is the list with (->first and ->last properties), and an "apple" is an element of that list with a (->next property). How does this for loop work?

typedef struct
{
    list_element header;
    int value;

} apple;

int main()
{
    list apples;
    apple * a = (apple *) malloc(sizeof(apple));
    apple * b = (apple *) malloc(sizeof(apple));
    apple * c = (apple *) malloc(sizeof(apple));

    a->value = 1;
    b->value = 2;
    c->value = 3;

    list_init(&apples);

    list_push_back(&apples, &a->header);
    list_push_back(&apples, &b->header);
    list_push_back(&apples, &c->header);
    for (a = (apple *) list_begin(&apples); a; a = (apple *) list_next(&a->header))
    {
        printf("%d\n", a->value);
    }

How does this for loop work?? The list_begin function just returns the ->first of apples. The ;a; as the conditional statement is saying if not 0 then continue the for loop? and the last part is pointing a to its next element in the loop. So when the last value of the loop is a=0 is that what would terminate the for loop?

Does that make sense?

Upvotes: 1

Views: 1323

Answers (2)

Gaurav
Gaurav

Reputation: 1600

The for loop is for traversing from the first node to the last node (until) it finds NULL (its for traversing the entire Linked List)..

The first parameter: a = (apple *) list_begin(&apples) puts a at the beginning of that list.

The second parameter: a is a condition and it gets violated on reaching one past the last node as it will be NULL.

The thirst parameter: a = (apple *) list_next(&a->header) is for traversing down the list.

Upvotes: 4

P.W
P.W

Reputation: 26800

The documentation of for will help you:

for ( init_clause ; cond_expression ; iteration_expression ) loop_statement 

Explanation
Behaves as follows:
... cond_expression is evaluated before the loop body. If the result of the expression is zero, the loop statement is exited immediately.

In your case, the cond_expression is just a and when a is zero (or NULL in case of pointer), the loop exits.

Upvotes: 3

Related Questions