In most programming languages, arguments passed to a function are evaluated before the function uses them, that is, they are evaluated eagerly.
To me, it seems like it would make much more sense to evaluate the arguments only once the function uses them, that is, lazily. This makes more sense to me because it seems like it would have a performance benefit: why evaluate things that are never even needed?
Moreover, suppose you wanted to implement an if
function that accepts a boolean, and an object to return if the boolean is true, and another object to return if the boolean is false:
object if(bool condition, object valueIfTrue, object valueIfFalse) {
if(condition) return valueIfTrue;
return valueIfFalse;
}
In a language that eagerly evaluates arguments, both objects are always evaluated even though the function will always only need one of them, which, at best, incurs a slight unecessary overhead, and, at worst, causes an infinite loop.
That said, since most programming languages use eager evaluation of function arguments, I assume there must be a reason why it's usually done that way. Is there some big benefit of eager evaluation here that I'm overlooking, is it just because it was easier to implement languages that way, is it just tradition, or what?