Zitat Zitat von Cherry
Code:
Print Sgn(Abs(CInt(&h80000000)))
Sleep
What is the output of this program going to look like?

"1", one would probably think.

You are wrong, it's "-1".

But mind you, this is not a bug. It's merely a result of how signed integers work. The absolute value of a number with only the highest bit set (in any kind of integer, so it applies to Byte, Short, Integer and LongInt) will be negative! Actually, Abs(x) will return x in this case.

Think about it! The range of a signed 32-bit integer goes from -2147483648 (-&h80000000, which is +&h80000000 if you cast treat it as unsigned!) to +2147483647 (+&h7FFFFFFF). The absolute value of -2147483648 would be +2147483648, but this value needs 33 bits including the positive sign bit! Thus, an overflow occurs and the 32-bit value returned by Abs() will again be -2147483648.

A variation of this pitfall is:
Code:
Dim x As Integer
Input x
If x = -x Then Print "Neutral number!" Else Print "Non-neutral number!" 
Sleep
This code will output "Neutral number!" if you input 0, but also if you input 2147483648 or -2147483648!

Just keep this in mind. It might produce some nasty bug one day if you blindly assume that Abs(x) will never be a negative number!

This kind of bug even slipped into the Windows kernel and stayed there for decades.
Interessiert euch vielleicht auch.