Hacker News new | comments | show | ask | jobs | submit login
Why MulDiv(1, -0x80000000, -0x80000000) returns 2 instead of 1? (msdn.com)
14 points by gus_massa 1897 days ago | hide | past | web | 5 comments | favorite

In my view, anyone using -0x80000000 in C is walking a thin line between being a guru and just being confused. :)

If it's not obvious, assuming a 32-bit integer, -0x80000000 equals 0x80000000 which equals -2147483648 which equals INT_MIN.

The unary negation operator causes overflow, making the result negative again.

Here's a simple program that prints these values: http://codepad.org/dFBRabf9.

AFAIK, assuming a 32-bit integer, 0x80000000 triggers undefined behavior. It might produce INT_MIN, blow up your computer, bring world peace, etc. It is true that many implementations do modular arithmetic, but assuming that makes your code platform dependent. So, I think you would be past that thin line.

I think -0x80000000 is perfectly valid, but that depends on the grammar. If that gets parsed as "apply negation operator to 0x80000000", it triggers undefined behavior. If it gets parsed as a negative constnat value, things are OK.

In either case, chances are INT_MIN is the better way to write it.


It has a different bug. The Wine version returns 0, the Windows version returns 2, a non-buggy version should return 1.

...and if you're interested in the code in question, it's here:


Couldn't even search for the bug as I saw this: http://source.winehq.org/source/dlls/kernel32/kernel_main.c#...

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact