AndrewBGS
Member
|
If statement evaluation
I just want a confirmation on this if I am right;
In EE, an IF statement is evaluated only to the point when the logic value of the result can be established?
In other words, If I have if(A and B) and A is false, B won't be evaluated?
I found this bit of code in Esenthel RPG:
if(Players.elms() && Players[0].alive()) - that made me think the way above is how if statements are evaluated. Am I right? (I always get a lot into details)
|
|
06-19-2013 12:21 PM |
|
Sherincall
Member
|
RE: If statement evaluation
In C/C++, the order for && and || is guaranteed to be left to right and evaluation stops as soon as the result can be determined. I'm certain it is the same in Esenthel Script.
That example is one of the most common uses. If you didn't check if there are any players before accessing Players[0].something, the program could crash if there were no players.
Note however that only && and || have that property. Bitwise operations (|, &, ^) don't. Also, only with && and || can you assume the left side will be evaluated first.
Example:
f0 and f1 are functions which print and then return 0 and 1 respectively.
Code:
if (f0() && f1()) // Prints 0, condition is false
if (f1() && f0()) // Prints 10, condition is false
if (f1() || f0()) // Prints 1, condition is true
if (f1() | f0()) // Can print either 10 or 01, condition is true
if (f0() & f1()) // Can print either 10 or 01, condition is false
if (f0() + f1()) // Can print either 10 or 01, condition is true
etc
(This post was last modified: 06-19-2013 01:39 PM by Sherincall.)
|
|
06-19-2013 01:34 PM |
|
laugan
Member
|
RE: If statement evaluation
Yep, it's called Short-circuit Evaluation.
The second argument is only executed or evaluated if the first argument does not suffice to determine the value of the expression.
More is here LINK
|
|
06-19-2013 01:34 PM |
|
Sherincall
Member
|
RE: If statement evaluation
Esenthel script is parsed into classic C++, which is then compiled using a standard compiler, such as VC++. It would actually be a hassle to change it, and you'd end up losing a feature.
If you really want both sides evaluated, you can use:
(A | B) instead of (A || B)
(!!A & !!B) instead of (A && B). !! isn't needed if A/B are booleans.
|
|
06-19-2013 02:41 PM |
|