Re: ++i++ for iterator in loops (gcc-3.4.4)
On Feb 6, 1:30 pm, Frank Bergemann <FBergem...@web.de> wrote:
i stumbled this in source code review:
VALID(?!):
======
No.
frank@frank-desktop:~$ cat test.cc
#include <iostream>
#include <list>
int main()
{
std::list<int> values;
values.push_back(1);
values.push_back(2);
values.push_back(3);
values.push_back(4);
values.push_back(5);
values.push_back(6);
for (std::list<int>::const_iterator i = values.begin();
i != values.end();
++i++) { // ### SEE THIS
This is ++ (i ++). The result of i ++ is not an lvalue, and the
standard doesn't require prefix ++ to work on non-lvalues. If
the iterator is a class type (almost certainly the case for
std::list, but not a formal requirement---and implementations
have used a simple T* for std::vector), and the prefix operator
++ is a member function (often the case, but it could just as
easily be a free function), then the code will compile, calling
prefix ++ on the temporary which is returned from the postfix
++, which effectively makes the prefix incrementation a no-op.
(The temporary is destructed at the end of the full expression.)
std::cout << "i is " << *i << std::endl;
}
return 0;
}
frank@frank-desktop:~$ ./test
i is 1
i is 2
i is 3
i is 4
i is 5
i is 6
As you can see, only one incrementation is taken into account.
The prefix ++ increments a temporary, which is then destructed.
NOT VALID:
=======
frank@frank-desktop:~$ cat test.cc
#include <iostream>
#include <list>
int main()
{
for (int i = 1;
i < 7;
++i++) {
std::cout << "i is " << i << std::endl;
}
return 0;
}
doesn't compile:
frank@frank-desktop:~$ g++ -o test test.cc
test.cc: In function =BBint main()=AB:
test.cc:8: Fehler: Ung=FCltiger L-Wert in Erh=F6hung
So why behaves iterator different that integer?
Because in this case, the iterator is a class type, and the
implementation has chosen to make the prefix operator++ a member
function. Neither is required by the standard. The code might
compile, or it might not. And because it is undefined behavior,
it might do anything if it compiles, although in practice, I
can't imagine anything other than what you are seeing: prefix ++
being called on a temporary.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34