Why do shift operators undergo integral promotion?

Timon Gehr timon.gehr at gmx.ch
Tue Aug 9 16:21:27 PDT 2011


Jonathan M Davis wrote:
> Walter Bright wrote:
>> On 8/9/2011 3:04 PM, Jonathan M Davis wrote:
>> > Hmmm. It seems to me that the question is whether anyone would ever
>> > _intentially_ use this behavior. Is there any benefit to it whatsoever?
>> > If not, I'd argue that the risk of breakage to C code being ported over
>> > is minimal and that the behavior should be fixed in D. Now, if there
>> > _is_ a benefit to it such that someone would use it intentionally, then
>> > that's another story, but it sure likes like the only reason that it
>> > would occur in C code would be because the programmer who wrote it
>> > screwed up.
>> >
>> > Now, that's still going to change the behavior of any code which used
>> > this behavior - even if it was by accident - which risks making code
>> > fail to work even if it only worked through a miracle before (i.e. in
>> > spite of the bug). So, maybe that's enough that we can't fix it. But it
>> > sure seems like the risk of new breakage is very low, since code whose
>> > behavior would change was broken in the first place, and I'd hate to see
>> > D's behavior stay like this if we can fix it.
>>
>> I don't see why it's a miracle that s>>1 would yield an int result.
>>
>> Do any of the C lints flag this as a bad practice?
>
> Then I'm misunderstanding something here. It was my understanding that this >
was yielding results which pretty much any programmer would consider
> incorrect or undesirable. As such, when this issue pops up, it yields an incorrect
> result, so the code is broken, and if it works, it's because something else
> gets around the issue (hence the miracle). If this isn't actually yielding
> effectively incorrect results, then it's a different issue entirely.
>
> So, I'm obviously misunderstanding exactly what the issue is - probably at
> least in part because I rarely need to use bitshifts.
>
> - Jonathan M Davis

I think what can be surprising is that s >>> 1 sign-extends s prior to the
unsigned right shift.

void main() {
    short s=-1;
    assert(s>>>1 == 2147483647);
    s=-1;
    s>>>=1;
    writeln(s == 32767);
}




More information about the Digitalmars-d mailing list