tags:

views:

244

answers:

2

I don't know how and why this piece of code works:

// postorder dfs
Iterator< Index<String<char> >, TopDown<ParentLink<Postorder> > >::Type
     myIterator(myIndex);
while (goDown(myIterator));
for (; !atEnd(myIterator); goNext(myIterator)) 
// do something with myIterator ( Traverse Through (Suffix)-tree )

It's an example from seqan and the interface is described here: API

  1. How can the while affect the for-loop?
  2. Why isn't the for loop initialized?
+15  A: 

You've run into the fun parts of C++ - using language constructs in syntactically valid but difficult-for-human-parsing techniques.

while (goDown(myIterator));

This will "goDown(myIterator)" until it returns false. Then it will continue onto the for loop. It's looping over nothing - but that's okay, because the function goDown is doing work.

for (; !atEnd(myIterator); goNext(myIterator))

This doesn't initialize anything, but tests that it's not atEnd(myIterator) - while it's not, it will goNext(myIterator). It could also be written as a while loop to make it slghtly easier to understand:

while(!atEnd(myIterator)) 
{
    goNext(myIterator));
}

So the code will:

  1. Go down until goDown() returns false - this means goDown is modifying myIterator each time
  2. goNext() until it is atEnd()
Tom Ritter
+4  A: 

Clearly, goDown and goNext are taking their argument by reference and altering it. So the answer to your two questions is, 1. the while calls goDown a number of times, altering myIterator as it goes, and this is the indirect influence you're talking about, since 2. the for starts with myIterator exactly as the while left it -- so of course it doesn't reassign it, that would undo all the while's work!

Alex Martelli