Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| From | Keith Thompson <kst-u@mib.org> |
|---|---|
| Newsgroups | comp.lang.c |
| Subject | Re: left shift count >= width of type |
| Date | 2011-11-02 13:47 -0700 |
| Organization | None to speak of |
| Message-ID | <ln62j2i74e.fsf@nuthaus.mib.org> (permalink) |
| References | <9hcichF56iU1@mid.individual.net> <j8r9rk$5u0$1@dont-email.me> |
James Kuyper <jameskuyper@verizon.net> writes:
[...]
> There's no guarantee that the shift count >= the width of the type,
> since 'int' could be, for instance, a 64-bit type.
>
> The relevant clause is phrased in terms of whether not the the result
> can be represented in the type, not the width of the type, For the
> expression E1 << E2, "If E1 has a signed type and nonnegative value, and
> E1 x 2^E2 is representable in the result type, then that is the
> resulting value; otherwise, the behavior is undefined" (6.5.7p5)
>
> Therefore, for a 32-bit int, even 1 << 31 is problematic. That's an
> example of why it's better to use unsigned types for most bit-masking
> purposes.
>
> However - and this is the key point - this is not a constraint, it's
> undefined behavior. Conforming implementations are NOT required to issue
> a diagnostic.
In addition (C99 6.5.7):
If the value of the right operand is negative or is greater than or
equal to the width of the promoted left operand, the behavior is
undefined.
So for a 32-bit type, even 0<<32 or 0>>32 has undefined behavior, even
though the mathematical result is representable.
[...]
--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
left shift count >= width of type Alessandro Basili <alessandro.basili@cern.ch> - 2011-11-02 10:55 +0100
Re: left shift count >= width of type James Kuyper <jameskuyper@verizon.net> - 2011-11-02 07:34 -0400
Re: left shift count >= width of type Keith Thompson <kst-u@mib.org> - 2011-11-02 13:47 -0700
Re: left shift count >= width of type Alessandro Basili <alessandro.basili@cern.ch> - 2011-11-04 17:46 +0100
Re: left shift count >= width of type James Kuyper <jameskuyper@verizon.net> - 2011-11-04 13:12 -0400
Re: left shift count >= width of type Alessandro Basili <alessandro.basili@cern.ch> - 2011-11-05 19:17 +0100
Re: left shift count >= width of type Thad Smith <ThadSmith@acm.org> - 2011-11-02 20:22 -0600
csiph-web