digitalmars.D - Increment/Decrement Boolean Operators
- AJG (29/29) Sep 21 2005 Hi there,
- Oskar Linde (23/55) Oct 07 2005 Isn't bit supposed to behave as a 1-bit integer? In that case, foo++ and
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
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