Jonathan Chiou
Jonathan Chiou

Reputation: 359

Trying to have 2 list iterators in a for loop

I'm trying to iterate through 2 linked lists with this for loop:

    for (ListNode* thisCurrent = head, ListNode* current = s.head; thisCurrent != NULL,   
        current != NULL; thisCurrent = thisCurrent->next) {
            //do something
    }

(Note: there is an implicit parameter of this)

If I have one iterator, the program will compile perfectly, but if I try to add in a second one (as shown above), the program will not compile at all. Errors I get are:

Expected initializer before the * token
'current' is not declared in this scope

How do I validly declare the for loop such that thisCurrent and current will both be created?

Upvotes: 1

Views: 49

Answers (1)

timrau
timrau

Reputation: 23058

It should be written as:

for (ListNode* thisCurrent = head, *current = s.head; thisCurrent != NULL,   
    current != NULL; thisCurrent = thisCurrent->next) {

Do not write the type name ListNode twice. Also, please review your loop termination condition since the result of thisCurrent != NULL has no effect at all.

Upvotes: 2

Related Questions