D arithmetic problem
Steven Schveighoffer
schveiguy at yahoo.com
Thu Jun 4 07:05:46 PDT 2009
On Thu, 04 Jun 2009 02:00:27 -0400, Don <nospam at nospam.com> wrote:
> bearophile wrote:
>> Denis Koroskin:
>>> Shouldn't bitwise operations be disallowed on signed types at all?
>> It sounds OK to me, do Don & Walter agree?
>
> Hmm. If you are doing bitwise operations, you are treating the number as
> unsigned, no doubt about it. Some observations:
>
> * The use of -1 for "all bits set" is in widespread use and is important.
>
> ushort x ^= -1;
> uint y ^= -1;
> ulong z ^= -1;
> probably needs to remain valid.
> But then consider
> (x ^ -1) + y
>
> What is the type of x^-1 ? Is it ushort? Or int?
>
> * A lot of existing C code uses bitwise operations on ints.
> * size_t had better be unsigned!
Easy:
~0. It's not even extra characters :) I'd say I use that way more than
-1 (which is probably never).
That being said, I readily type int WAY more than uint when keeping track
of any integral type, including using bitmasks. If I don't ever use the
sign bit in my bitmask, it doesn't matter.
Also, think about porting code from Java which has no unsigned types. You
don't want to have to sit and think about what each variable really means
(should it be converted to uint?).
So I think logic operations on signed types should be allowed, but being
able to use -1 as "all bits set" isn't a good argument for it. I'd much
rather see an error for the uncommon widening operations without an
explicit cast.
-Steve
More information about the Digitalmars-d
mailing list