Re: Variables in "for" Loop
Johannes Schaub (litb) wrote:
Volkan YAZICI wrote:
Hi,
Why does
for (list<string> newlines = frame(oldlines),
list<string>::iterator line = newlines.begin();
line != newlines.end();
++line)
not work, while
list<string> newlines = frame(oldlines);
for (list<string>::iterator line = newlines.begin();
line != newlines.end();
++line)
does?
Regards.
Because you cannot declare variables of that much differing types in a
forloop's init declaration. It must be a single block-declaration. So all
declared names must have the same base-type, tho they can differ by
pointer/reference/function declarators. A way around this is to use a
nameless struct
for(struct { list<string> newlines; list<string>::iterator line; }
loop = { frame(oldlines), loop.newlines.begin() };
loop.line != loop.newlines.end(); ++loop.line)
{ ... }
Ah, seems I've fallen into a trap. C++03 does not define the order in which
the members are initialized, neither the order in which the elements in the
initializer list are evaluated. C++0x specifies the order in which the
elements of the initializer list are evaluated, but doesn't specify the
order in which the elements are initialized either, it seems.
So the "loop.newlines" is not safe to use because there is no guaranteed
that the list was already created at that point. :(