www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Increment/Decrement Boolean Operators

reply AJG <AJG_member pathlink.com> writes:
Hi there,

I noticed that the Increment/Decrement operators are defined for type bool,
which is in turn, type bit. I dunno whether this is intended or not. Thinking
about it, they could be quite useful:

bool foo;
foo++; // Make foo = true.
foo--; // Make foo = false.
// etc.

However, this works only so far. In fact, it subly works but could blow up in
your face.

Internally, bit is still an integer of some sort, therefore using those
operators actually changes the quantity just like a regular integer. In other
words, it has nothing to do with on/off which is what a boolean is about.

For instance:

void main() {
bool Bar = false;
assert(!Bar); // OK.
Bar++;
assert(Bar);  // OK.
Bar++;
assert(Bar);  // OK.
Bar--;
assert(!Bar); // Fails.
}

Given what I said, that last assert should have passed. Since bit is an on/off
type and not a numerical type, I think these operators are not working properly.
They should be overridden for booleans appropiately.

Cheers,
--AJG.
Sep 21 2005
parent Oskar Linde <olREM OVEnada.kth.se> writes:
AJG wrote:

 Hi there,

Hello,
 I noticed that the Increment/Decrement operators are defined for type
 bool, which is in turn, type bit. I dunno whether this is intended or not.
 Thinking about it, they could be quite useful:
 
 bool foo;
 foo++; // Make foo = true.
 foo--; // Make foo = false.
 // etc.

Isn't bit supposed to behave as a 1-bit integer? In that case, foo++ and foo-- should overflow giving equal behavior to ++ and --: toggling the bit. Disregarding the integer promotion rules that prevent this, foo++; should do the same thing as foo = foo + cast(bit)1;
 However, this works only so far. In fact, it subly works but could blow up
 in your face.

IMHO, foo++, and foo-- works as they should: modulo 2 arithmetics.
 Internally, bit is still an integer of some sort, therefore using those
 operators actually changes the quantity just like a regular integer. In
 other words, it has nothing to do with on/off which is what a boolean is
 about.
 
 For instance:
 
 void main() {
 bool Bar = false;
 assert(!Bar); // OK.
 Bar++;
 assert(Bar);  // OK.
 Bar++;
 assert(Bar);  // OK.
 Bar--;
 assert(!Bar); // Fails.
 }

I am unable to reproduce that. I get: void main() { bit bar = 0; assert(!bar); // OK bar++; assert(bar); // OK bar++; assert(!bar); // OK bar--; assert(bar); // OK } (with dmd 0.133 linux)
 
 Given what I said, that last assert should have passed. Since bit is an
 on/off type and not a numerical type, I think these operators are not
 working properly. They should be overridden for booleans appropiately.

In my opinion, bits/bools should (and do, as far as I can tell) follow the rules of modulo 2 arithmetics. Regards Oskar Linde
Oct 07 2005