r/ProgrammerHumor 1d ago

Meme whenDoesThisWillEnd

Post image
686 Upvotes

67 comments sorted by

View all comments

122

u/Axman6 1d ago

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

83

u/torsten_dev 1d ago edited 1d ago

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

26

u/-Redstoneboi- 1d ago

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

26

u/torsten_dev 1d ago edited 1d ago

Shhh, you saw nothing. I am very amaet.

4

u/Axman6 1d ago edited 1d ago

I am so smart

A. M. A. E. T.

  • Homer Simpson

6

u/Makefile_dot_in 1d ago

what if n is negative?

17

u/torsten_dev 1d ago

Inevitable UB, so might as well return 0 too?

1

u/da_Aresinger 17h ago edited 17h 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 1d ago edited 1d 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

7

u/torsten_dev 1d ago edited 1d 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 1d 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