?
Z schrieb:
krümelkacker schrieb:
Ich halte es für wichtig, darauf hinzuweisen, was der Sprachstandard garantiert und was er nicht garantiert. Er garantiert nicht, dass char vorzeichenbehaftet ist. Er garantiert nicht, dass (-3<<1)==(-6) gilt.
Ich denke schon, daß der Standard (-3)<<1 == -6 garantiert, sofern diese -3 ein Integer-Typ ist. Ich verwende C++ schon seit vielen Jahren und bisher bin ich von dieser wunderbaren Programmiersprache noch nicht enttäuscht worden.
Und genau deswegen halte ich es für wichtig darauf hinzuweisen. Viele -- wie anscheinend Du auch -- gehen davon aus, dass dieses Verhalten garantiert ist.
Im Entwurf des C++ Standards von 2005 kann man nachlesen:
Shift Operators, §5.8/2-3:
The value of E1 << E2 is E1 (interpreted as a bit pattern) left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 multiplied by the quantity 2 raised to the power E2, reduced modulo ULONG_MAX+1 if E1 has type unsigned long, UINT_MAX+1 otherwise. [ Note: the constants ULONG_MAX and UINT_MAX are defined in the header <climits>. — end note ]
The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 divided by the quantity raised to the power E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.
implementation-defined behavior, §1.3.6:
behavior, for a well-formed program construct and correct data, that depends on the implementation and that each implementation documents.
Fundamental types, §3.9.1/1,7:
[...] It is implementation-defined whether a char object can hold negative values. [...]
[...] The representations of integral types shall define values by use of a pure binary numeration system. [ Example: this International Standard permits 2’s complement, 1’s complement and signed magnitude representations for integral types. — end example ]
==>
| -3 | -3 << 1
--------+--------------+------------------
2's cmp | 111...111101 | 111...111010 (-6)
1's cmp | 111...111100 | 111...111000 (-7)
sgn+mag | 100...000011 | 000...000110 ( 6)
Q.E.D.