Re: behaviour of simple short -> int conversion differs in debug and release version
P@ <p.hoffmann@berlin.de> wrote:
The following code prints out -1 in debug mode (correct) and 0 in
release mode (wrong) if compiled with Visual Studio.NET 2003.
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
short usVal;
// enter -1
std::cin >> usVal;
int iVal = usVal;
iVal = iVal >> 17;
std::cout << iVal << std::endl;
return 0;
}
Looks like a bug. If one looks at the disassembly, the shift is elided
entirely and a constant 0 is output to cout. Apparently, the compiler
erroneously assumes the value would always be zero-extended, and thus
believes it can calculate the shift at compile time.
I don't have VC8 handy at the moment to check how it behaves in this
case.
Be aware that the code is non-portable. C++ standard:
5.8/3 The value of E1 >> E2 is E1 right-shifted E2 bit positions... If
E1 has a signed type and a negative value, the resulting value is
implementation-defined.
MSDN specifies that VC compiler is indeed supposed to propagate most
significant bit to fill vacant positions, and thus -1 is the correct
output in your example. Other implementations may differ.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925