+ 1
How does the "if" work?
Lets say i have something like: if(checkSomething() && checkSomethingElse()){...} Where checkSomethingElse() does a api call. If checkSomething() returns false, does the second function get called? I was wondering if this would do useless api calls whenever the first function returns false
4 Answers
+ 6
đ Alex TuČinean đ you didn't mention which language, but that's no matter. All the languages in which that syntax is valid do short-circuit conditional evaluation as you described. It is evaluated left-to-right. If the first condition is False, then the second condition will not get evaluated. That also means it will not even call the second function.
+ 3
In this case you have used logical and operator (&&) where if both are true then it's true otherwise it's false.
In addition both functions will be called and return true or false based on the function criteria and if overall it is true it will enter inside the if statement and execute the statements otherwise it won't execute.
+ 2
2nd function may execute in case by mistake if you used single '&'
+ 1
checkSomething() will be true if it returns anything that's not explicitly false or the integer, 0, Then checkSomethingElse() will be called no matter what
Otherwise checkSomething () is false and only checkSomethingElse() will be called, no matter the condition.
In mathematics, these type of expression under logical reasoning are called "bidirectional statement" and "converse statement" for both instances respectively.
if P and Q are any statement, the likely result falls under
p <=> q
p => q
in both cases, Q is always evaluated