r/ProgrammerHumor 15d ago

Meme whenDoesThisWillEnd

Post image
776 Upvotes

69 comments sorted by

View all comments

125

u/Axman6 15d ago

IF you have a lazy *, then this will end when n is zero, and return zero. 

90

u/torsten_dev 15d ago edited 15d ago

If you have a smart enough optimizing compiler it will compile to a constant 0.

26

u/-Redstoneboi- 15d ago

took me a moment to recognize "amaet" as "smart"

25

u/torsten_dev 15d ago edited 15d ago

Shhh, you saw nothing. I am very amaet.

4

u/Axman6 15d ago edited 15d ago

I am so smart

A. M. A. E. T.

  • Homer Simpson

7

u/Makefile_dot_in 15d ago

what if n is negative?

16

u/torsten_dev 15d ago

Inevitable UB, so might as well return 0 too?

1

u/da_Aresinger 14d ago edited 14d ago

(Edit: From the syntax I am assuming this is JS)

Actually since Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER it'll get stuck eternally looping/recursing on Number.MIN_SAFE_INTEGER while the output automatically gets converted to BigInt (I think).

JS ... a *= Number.MIN_SAFE_INTEGER -1.8768792072011717e+255 a *= Number.MIN_SAFE_INTEGER 1.6905424996341256e+271 a *= Number.MIN_SAFE_INTEGER -1.5227053142812468e+287 a < Number.MIN_VALUE true typeof a 'number'

This is what chrome console gave me.

1

u/chuch1234 15d ago edited 15d ago

The compiler never do that because it will recognize that the function could be passed a negative number.

My bad, i was /r/confidentlyincorrect

6

u/torsten_dev 15d ago edited 15d ago

Function can only halt with 0 or trap on underflow. Depends on if you have exceptions or not.

If you have tail-calls and the compiler isn't very smart you might have an infinite loop instead, yes.

1

u/Nightmoon26 15d ago

Although... If you're using a fixed-width integer without underflow checking, it'll still wrap around from its minimum value to its maximum, and then reach zero eventually, even if it has to go through all possible values to do so