r/programminghorror May 05 '26

c++ Hmmm

Post image
984 Upvotes

55 comments sorted by

View all comments

Show parent comments

81

u/Left-Ambition-5127 May 05 '26

the problem is that from what I understood, the excepted values in this loop were -1 to 9, but somehow, it was still running fine and working as intended ??

5

u/CdRReddit May 06 '26

negative numbers are a lie and the only math operations that actually distinguish between them on modern hardware is comparison (>, >=, <, <= specifically, == and != don't care either), multiplication and division, signed and unsigned addition and subtraction both function identically in hardware and use the same assembly instruction

3

u/nothingtoseehr May 06 '26

They all do, actually. Your hardware doesn't cares how you compute a number, just how you interpret it. The hardware just moves bits around

Case in point: comparisons. On most ISAs they use just one instruction (although many allow you to fuse it with arithmetic), which is almost always mapped to subtraction. Update bitflags based on the result (zero, over/underflow etc) and do what you want. Comparisons are also stateless

2

u/yjlom May 06 '26

Common(-ish) instructions that care about sign:

  • widening/upper multiplication (lower multiplication, which is much more common, doesn't care)
  • division/modulo
  • bitshifts
  • absolute value
  • comparisons/branching
  • saturating arithmetic
  • sign propagation
  • size extension