C++ Logo

sg12

Advanced search

Re: [ub] ub due to left operand of shift

From: Lawrence Crowl <Lawrence_at_[hidden]>
Date: Wed, 30 Oct 2013 17:40:00 -0700
On 10/27/13, Jens Maurer <Jens.Maurer_at_[hidden]> wrote:
> On 10/28/2013 04:24 AM, Lawrence Crowl wrote:
>> Sigh, I think promoting unsigned to signed is broken, but I do
>> not think we can change it. Does any compiler have a warning
>> for this behavior?
>
> Sure, gcc does:
>
> int main(int argc, char **argv)
> {
> unsigned int x = (unsigned char)argc << 7;
> }
>
>> g++ -Wsign-conversion shift.cc
> shift.cc: In function ‘int main(int, char**)’:
> shift.cc:3:43: warning: conversion to ‘unsigned int’ from ‘int’ may change
> the sign of the result [-Wsign-conversion]

And is it useful in programs that include standard headers?

>>> In other words, we've already fixed this one (for some value
>>> of "fixed").
>>
>> Right, we defined it to be what people were getting already.
>> While I think that was the only really practical choice, I would
>> rather see a less permissive option available to programmers
>> that do not want to stray from "mathematically expected" results.
>
> You can always define your own "lshift" function with the appropriate
> asserts, right?

Yes, but operators are nice and the more work people have to do to
get solid behavior, the less likely they are to go after it.

-- 
Lawrence Crowl

Received on 2013-10-31 01:40:02