Hacker News new | ask | show | jobs
by ninkendo 1215 days ago
I think the idea is that if there's observable behavior in unconditionally calling the expensive function, the compiler can't skip it without altering the program behavior. Whereas if they're called as part of the if condition, the compiler can always safely skip the second function (and it's documented that it must do so, due to "short circuit" semantics) if the first function is false.

The ability of the compiler to skip the expensive function in both cases are characteristics of a "lazy" language, ie. you can assign an expensive function to a value, but the actual function isn't run until the variable is needed. Languages like C++ can't do this because it would alter the program's behavior if cheapCheck() does return true, because suddenly it would have to call expensiveCheck() after cheapCheck() (rather than before), which is an observably different behavior for the optimization to cause.

1 comments

My mistake for reading HN too early in the morning. You and the other poster are right.
(Fun fact: I read meindnoch's comment right after I woke up and I, too, was about to reply to them with a godbolt listing to show that it would compile to the same thing, only to realize I completely forgot about short-circuit semantics. So you're not alone!)