c++ - Why does left shift operation invoke Undefined Behaviour when the left side operand has negative value? -
c++ - Why does left shift operation invoke Undefined Behaviour when the left side operand has negative value? -
in c bitwise left shift operation invokes undefined behaviour when left side operand has negative value.
relevant quote iso c99 (6.5.7/4)
the result of e1 << e2 e1 left-shifted e2 bit positions; vacated bits filled zeros. if e1 has unsigned type, value of result e1 × 2e2, reduced modulo 1 more maximum value representable in result type. if e1 has signed type , nonnegative value, , e1 × 2e2 representable in result type, resulting value; otherwise, the behavior undefined.
but in c++ behaviour defined.
iso c++-03 (5.8/2)
the value of e1 << e2 e1 (interpreted bit pattern) left-shifted e2 bit positions; vacated bits zero-filled. if e1 has unsigned type, value of result e1 multiplied quantity 2 raised powerfulness e2, reduced modulo ulong_max+1 if e1 has type unsigned long, uint_max+1 otherwise. [note: constants ulong_maxand uint_maxare defined in header ). ]
that means
int = -1, b=2, c; c= << b ; invokes undefined behaviour in c behaviour defined in c++.
what forced iso c++ commission consider behaviour defined opposed behaviour in c?
on other hand behaviour implementation defined bitwise right shift operation when left operand negative, right?
my question why left shift operation invoke undefined behaviour in c , why right shift operator invoke implementation defined behaviour?
p.s : please don't give answers "it undefined behaviour because standard says so". :p
the paragraph copied talking unsigned types. behavior is undefined in c++. lastly c++0x draft:
the value of e1 << e2 e1 left-shifted e2 bit positions; vacated bits zero-filled. if e1 has unsigned type, value of result e1 × 2e^2, reduced modulo 1 more maximum value representable in result type. otherwise, if e1 has signed type , non-negative value, , e1×2e^2 representable in result type, resulting value; otherwise, behavior undefined.
edit: got @ c++98 paper. doesn't mention signed types @ all. it's still undefined behavior.
right-shift negative implementation defined, right. why? in opinion: it's easy implementation-define because there no truncation left issues. when shift left must not what's shifted right happens rest of bits e.g. two's complement representation, story.
c++ c language-lawyer undefined-behavior bit-shift
Comments
Post a Comment