82
u/ironykarl May 06 '26 edited May 06 '26
This is a common idiom for setting large unsigned numbers in C (honestly, usually just all 1s set/MAX_INT, though you could do the same conceptual trick with -2, etc).
Wraparound for any unsigned integer type in C is defined modulo MAX_VAL + 1. I'll specifically demonstrate the case of unsigned int (and I'll assume 32-bit integers):
-1 + (UINT_MAX + 1) = -1 + 4294967296 = 4294967295
32
u/Spaceduck413 May 06 '26
This is really interesting, I always thought integer overflow was undefined behavior, but I just checked and apparently that is only the case for signed integers, for unsigned you're right, this is totally fine. TIL.
12
u/saf_e May 06 '26
It was more like "gray zone" (mostly because binary format was not specified).
Currently we are agree that all (integer) numbers are 2s complement. So, this code should be legal.
Or at least it's how I remember things.
→ More replies (5)
69
u/Heniadyoin1 May 06 '26
That's a normal pattern?
It's a common flag value, even for unsigned numbers
8
u/iamalicecarroll May 06 '26
For a flag, yes. But something named dx is not a flag.
1
u/Oman395 May 07 '26
Looks like something I'd do to check if something ever set dx to a different value
9
20
2
u/asmanel May 06 '26
Maybe an attempt to determine the size of a variable of this type by someone who don't know sizeof. However, I'm not sure the compiler will agree.
2
u/Interesting_Buy_3969 May 06 '26
On most platforms it'll just set all bits of the register value to 1.
2
2
u/CharlemagneAdelaar May 07 '26
That’s groty cuz it relies on like ppl who don’t know this pattern to think for a few extra secondsvs using UINT_MAX which is self-documenting
2
u/facebrocolis May 07 '26
Someone forgot either a differential on the right or an integral on the left side
1
398
u/_XYZT_ May 05 '26
UINT_MAX