this post was submitted on 13 Dec 2025
274 points (97.9% liked)
Programmer Humor
39553 readers
11 users here now
Post funny things about programming here! (Or just rant about your favourite programming language.)
Rules:
- Posts must be relevant to programming, programmers, or computer science.
- No NSFW content.
- Jokes must be in good taste. No hate speech, bigotry, etc.
founded 6 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
The compiler should be able to optimize all of them to the same machine code.
x==10, so as long as thenextInt()method doesn't have side effects, the loop should be eliminated. But, again, language semantics can affect this.~~Edit: Very wrong for 3 & 4, see replies.
I'd be shocked if 4 got optimised out
I feel like an idiot. Also, in the "Good" example, no underflow occurs. i goes from 0 to -10, and x is assigned to -i every loop.
It might still be possible to optimize away the random number example, if the random function were made a magic language item, but it would not be even remotely close to being worth the effort.
The question the optimizer can't really answer is: will Random.nextInt() ever return 10? If that's a 64 bit integer it could be a LOOOOOONG time before 10 ever shows up.
Ah yes the halting problem
If it were a magic lang item, you could treat the resulting value in a special way. Then, you could create an optimization pass for this situation: if a variable is assigned random in a loop and the loop can only be exited with a certain value, the compiler can coerce the magic rand value to it.