When choosing a value based off of 2 boolean values in this formatvar foo:int;if (X){    foo = 50;} else if (Y){    foo = -50;} else {    foo = 0;}I discovered that I can condense this down by typecasting the boolean operations to integers,  and mathing it up a bit like so:var foo:int;foo = ( int (X) - int(!X && Y) ) * 50;// int() typecasts a boolean argument to an int of 1 if true, 0 if false.Here are my questions:Is this approach less resource intensive?Is this approach readable to you?Is assigning values in this way common?If 1 is true then in your opinion, does the performance increase justify the less readable nature of this approach?This situation arose in ActionScript 3.0, but I am interested in answers from all languages, and from a best practice perspective.
Boolean-Integer Typecasting to Replace Conditional
readability;data types;conditions;type casting
This is to some extent a matter of style, but I really believe your single-line option is much, much less readable, and is not a common approach.The first classic if is very easy to read and check. There's no complex nesting, just a plain, boring, chain of conditions that is well understood in all languages that have an if/else if/else construct.The second is very tricky:Two conditionals, one of them a composite for which you need to know operator precedence(is !X && Y interpreted as (!X) && Y or !(X && Y))Two casts for which you need to know that true is converted to 1 and false to 0 (or are those function calls?). This might be common, but it's something people aren't always aware of, or aware that the language guarantees that. (That is if you're indeed using a built-in cast in this example - if it's a custom function call, then that needs to be known too)Then you have to figure out what the result of that - operation will be in what circumstances. Pretty basic maths, but needs a few brain cycles more than the trivial if/else cascade.As for the second version could somehow be more efficient? I don't think so. In fact, it might be not only less efficient, but not behave the same way as the first. X is evaluated twice (so potentially more expensive). If the evaluation of X has side-effects, the two versions aren't equivalent.(And let's not mention C-type macros that could break the second version while the first works, or the issues with un-sequenced operations your second version could entail in C and C++ because of that double evaluation in a single statement - I don't think that's the point of your question here.)tl;dr: less lines of code does not mean more efficient. Your code should be written so that it can be efficiently maintained. Your compiler/runtime/interpreter will take care of the dirty work of optimizing as long as you've chosen the right algorithms and data structures and expressed them clearly in your language.