I Google'd so hard before I wrote this question. I am an "ok" C & C++ programmer, but not expert level. Everything that I read tells me that unsigned integer overflow is safe in C. However, signed integer overflow is "undefined behaviour" (UB). Oh, dreaded UB!
Related: Why is unsigned integer overflow defined behavior but signed integer overflow isn't?
Win32 API:
LONG InterlockedIncrement(
[in, out] LONG volatile *Addend
)
Ref: https://learn.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-interlockedincrement
To be clear, LONG
is defined as signed 32-bit int
.
By inspection (not defintion/docs), this Win32 API appears to support signed integer overflow.
Example code:
#include <stdio.h>
#include <windows.h>
#include <limits.h>
int main(int argc, char **argv)
{
printf("INT_MAX: %d\n", INT_MAX);
LONG zz = INT_MAX;
// Be careful about: 1 + 2,147,483,647 -> -2,147,483,648
const LONG zzz = InterlockedIncrement (&zz);
printf("INT_MAX+1: %d and %d\n", ((LONG) 1) + INT_MAX, zzz);
return 0;
}
When I compile on Cygwin with gcc
, then run, I see:
INT_MAX: 2147483647
INT_MAX+1: -2147483648 and -2147483648
I am confused.
- Do I misunderstand the rules of signed integer overflow for C?
- Does Windows have special rules?
- Is this argument theoretical in 2022 for Real World systems -- everything is 2's complement now?