I encountered a strange thing when I was programming under c++. It’s about a simple multiplication.
Code:
unsigned __int64 a1 = 255*256*256*256;
unsigned __int64 a2= 255 << 24; // same as the above
cerr()<<"a1 is:"<<a1;
cerr()<<"a2 is:"<<a2;
interestingly the result is:
a1 is: 18446744073692774400
a2 is: 18446744073692774400
whereas it should be:(using calculator confirms)
4278190080
Can anybody tell me how could it be possible?
all operands are
intyou are overflowingint. The overflow of a signed integer is undefined behavior in C and C++.EDIT:
note that the expression
255 << 24in your second declaration also invokes undefined behavior if yourinttype is32-bit.255 x (2^24)is4278190080which cannot be represented in a32-bitint(the maximum value is usually2147483647on a32-bitintin two’s complement representation).C and C++ both say for
E1 << E2that ifE1is of a signed type and positive and thatE1 x (2^E2)cannot be represented in the type ofE1, the program invokes undefined behavior. Here^is the mathematical power operator.