Re: enum and operator++
On Jan 20, 3:39 pm, REH <spamj...@stny.rr.com> wrote:
On Jan 20, 10:34 am, Saeed Amrollahi <amrollahi.sa...@gmail.com>
wrote:
On Jan 20, 6:21 pm, Yu Han <hanju...@163.com> wrote:
On 01/20/2010 11:07 PM, Saeed Amrollahi wrote:
I am struggling with a problem that's simple per se.
I have an enum and a prefix ++ operator:
enum Dir { North = 1, East = 2, South = 3, West = 4, Max_ = 5 }; //
clockwise
Dir operator++(Dir d)
{
Dir dd;
switch (d) {
case North:
dd = East;
break;
case East:
dd = South;
break;
case South:
dd = West;
break;
case West: // wrap
dd = North;
break;
};
return dd;
}
void f()
{
for (Dir d = North; d< Max_; ++d)
----->for (Dir d = North; d< Max_; d=++d)
// do something
}
The problem is: in the above loop the ++ doesn't work,
indeed the loop is infinite. If you replace // do something with
output statement, it prints 1 forever.
That's Excellent.
No it's not.
Why ++d isn't enough and we have to use d = ++d?
No, that is undefined behavior. Don't do it.
There's no undefined behavior given his definition of
operator++; in fact, it's rather difficult to get undefined
behavior with a user defined operator, because of the additional
sequence points it introduced.
There are, in fact, two problems with his code. The first is
that his operator++ doesn't actually increment anything; it just
returns the next value. Normally, an operator++ takes a
non-const reference as argument (or is a non-const member, but
that's not an option for enum's), and modifies its argument.
Anything else falls under the label of obfuscation, or lying to
the reader. The second reason is that because his operator++
wraps before reaching Max_, it can never cause the value to
become >= Max_; even a correctly written operator++ will result
in an endless loop with this definition of incrementation.
--
James Kanze