IF ELSE vs Select Case - excel

I wish to know how this would impact my coding when handling large volumes of data, and how I would construct my logic arguments
Two questions:
1) What are the main differences between IF-ELSE and Select CASE? Does select case operate by evaluating all cases at the same time?
If I have a situation where, by nature of its construction, need to fulfill two or more cases at the same time, for e.g.
int = 5
Select case int
Case >0
Case 5
Case <0
Where I would need to "trigger" both Cases "1" and "2" for action, do I use CASE over IF ELSE?
2) Now for the other case, if I have a variable that will trigger more one case but I would like to restrict to only one case by priority, say I would only like Case "1" for action and exclude the rest, am I right to say that IF-ELSE would triumph in this regard?
EDIT - I realized that my question was phrased poorly. I did some edits to the code

Some clarification on Select Case before actually answering your question:
as you suggested, you can combine several values in one Case switch in VBA, e.g.: Case Is>40, 20, 10, 2 To 3, for more information see documentation on MSDN
It'll execute at most one Case, it'll exit after finding a match (e.g. in the example execute Case >0 then exit without even evaluating Case 5)
It'll only evaluate your variable / expression once and use this same value for all comparisons in contrary to nested if which evaluates multiple time
if you want to execute "both" for a value you can nest if within case:
Case Is > 0
<Common code>
If i = 5 Then
<code only for case 5>
End If
Advantage of Select Case
It's more efficient when your decision is about multiple values of a single variant / expression
it also can be very useful when your expression is e.g. result of a time consuming function, in this case you really can save time compared to if
Advantage of If
Basically it's the good option in all the cases which are not described for Select Case e.g.:
you have only two options to choose from (it's the same time with both if and select, but if is easier to read)
you have multiple expressions to consider during decision and you can't easily convert them to a single value
Similarly to Select Case you can also use elseif to prepare multiple comparisons, it'll also stops at first fullfilled criteria, but here your expression will be evaluated every time until finding the match and of course you can use more complex criteria.

If-Else and Switch statement are good in different cases.
For example, If-Else has logic conditions like:
if (n < 5 && a > 5) { } // && is a logical AND
and nested constructions like
if (n < 5) {
if (n < 0)
{
}
else
{
}
} else { }
You cannot do this in switch statement.
However, switch is better, more elegant and faster in some situations:
switch (a)
{
case 1:
case 2:
case 3:
// ...
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 10:
break;
default:
break;
}
would look very bad in if-else format:
if (a == 1 || a == 2 || a == 3)
{
}
else
if (a == 4)
{
}
else
// ...
I'm not sure about your case but in most languages switch statement is more performant.
Simply said, use switch statement every time it is possible and there are more than two cases. If there are only two cases or it is impossible to use switch - use if.

Related

Why does the expression: If (A:=!A) evaluate differently each time a hotkey is pressed?

In an Autohotkey script, once a user presses the CapsLock key, a SplashText should pop up indicating that it is ON, or out when it is OFF, the problem here is not about the code that gets it to work but how much simpler it can get.
There are different ways that do it, some need about 25 lines, some use SetTimer and GetKeyState internal functions and several loops to get it to run, some just about five and no loops.
Simplest:
#SingleInstance Force
SetCapsLockState, Off
~CapsLock::
If (Tog:=!Tog)
SplashTextOn ,350 ,35 , Wanted !, [CapsLock] Activated.
else
SplashTextOff
return
How does: If (Tog:=!Tog) get this code running so easily? Tog is just a variable not initiated, and each time the CapsLock is pressed it is continuously changing its value from 1 to 0
It seems to be acting as a Flag in the code? what am I missing in this line:
If (Tog:=!Tog)
What makes it evaluate different each time?
This is one below is another approach with A = 0 working as a switch, I made this one and it doesn't quite get as simple as I'd like it to be but it does the job.
Longer code:
#SingleInstance Force
SetCapsLockState, Off
~CapsLock::
If (A = 0)
{
SplashTextOn ,350 ,35 , Wanted !, [CapsLock] Activated.
A=1
}else
{
SplashTextOff
A=0
}
return
Longest code:
This last one gets the same result but checks the actual physical state of the key It wouldn't rely on SetCapsLockState, Off at the top of the script to make sure a switch will do the rest of the work in just one line as the simpler one.
#SingleInstance Force
#Persistent
SetTimer, StateCapsLockON_Timer, 100
Return
~CapsLock::
StateCapsLockON_Timer
If GetKeyState("CapsLock", "T")
{
SetTimer, StateCapsLockOFF_Timer, 100
SplashTextOn ,350 ,35 , Wanted !, [CapsLock] Activated.
SetTimer, StateCapsLockON_Timer, Off
}
Return
StateCapsLockOFF_Timer:
If !GetKeyState("CapsLock", "T")
{
SetTimer, StateCapsLockOFF_Timer, Off
SplashTextOff
SetTimer, StateCapsLockON_Timer, On
}
Return
Any good ideas about the way If (Tog:=!Tog) works in the simplest of these three examples?
I got this now, check logical-not on this link:
https://lexikos.github.io/v2/docs/Variables.htm
If the operand (In this case Tog) is blank or 0, the result of applying logical-not (or !Tog) is 1, which means "true". Otherwise, the result is 0 (false)
if (Tog = 0)
Tog = 1
would bring the same result as:
If Tog:=!Tog
Because an operation was taking place before the If even checked the changed value, if wasn't just comparing data, the operation was happening before the if since the values inside the parenthesis were not just being read but were also being changed and the variable being reassigned.
(expression) Any sub-expression enclosed in parentheses. For example, (3 + 2) * 2 forces 3 + 2 to be evaluated first.
The key difference is the usage of the assignment operator := as opposed to the comparing operator =. Since, as you've seen, you can evaluate expressions in an if-statement, you can actually include both operators in the same if-statement. Here's an example:
f1::
If (( test := 3+2 ) = 5 )
MsgBox
Return
Here "test" is first being assigned the sum of 3+2, then compared to 5. So, the key is that if-statements allow assignments to take place and that assignments take place first, that is, before anything is compared and evaluated to be true or false.
If there is no comparing operator (= , <, >, <=, >=), as is the case in your toggle, it just evaluates whether the variable itself is true or false. If the variable is blank, 0, or false, it evaluates to false; everything else is true, even the string "false".
Now for the fun bit. We can actually reduce your code to one line if we use Progress with the "zh0" option.
~CapsLock::Progress , % ( Tog := !Tog ) ? "zh0 w350 h35" : "Off" ,, [CapsLock] Activated. , Wanted !
Unfortunately, this isn't possible with SplashText since these are actually two separate commands. But the upside is that Progress actually has a lot more options available, so you can change the font size and color, etc.

Why were Logical Operators created?

Almost all programming languages are having the concept of logical operator
I am having a query why logical operators were created. I googled and found its created for condition based operation, but that's a kind of usage i think.
I am interested in the answer that what are the challenges people faced without this operator. Please explain with example if possible.
I am interested in the answer that what are the challenges people faced without this operator.
Super-verbose deeply nested if() conditions, and especially loop conditions.
while (a && b) {
a = something;
b = something_else;
}
written without logical operators becomes:
while (a) {
if (!b) break; // or if(b){} else break; if you want to avoid logical ! as well
a = something;
b = something_else;
}
Of if you don't want a loop, do you want to write this?
if (c >= 'a') {
if (c <= 'z') {
stuff;
}
}
No, of course you don't because it's horrible compared to if (c >= 'a' && c <= 'z'), especially if there's an else, or this is inside another nesting. Especially if your coding-style rules require 8-space indentation for each level of nesting, or the { on its own line making each level of nesting eat up even more vertical space.
Note that a&b is not equivalent to a&&b: even apart from short-circuit evaluation. (Where b isn't even evaluated if a is false.) e.g. 2 & 1 is false, because their integer bit patterns don't have any of the same bits set.
Short-circuit evaluation allows loop conditions like while(p && p->data != 0) to check for a NULL pointer and then conditionally do something only on non-NULL.
Compact expressions were a big deal when computers were programmed over slow serial lines using paper teletypes.
Also note that these are purely high-level language-design considerations. CPU hardware doesn't have anything like logical operators; it usually takes multiple instructions to implement a ! on an integer (into a 0/1 integer, not when used as an if condition).
if (a && b) typically compiles to two test/branch instructions in a row.

Why is switch statement implemented the way it is in most languages?

pseudo code
int i=10
switch(i)
case 1:
print(1);
case 10:
print(10);
case 20:
print(20);
Intuitively this would be expected to print 10. But because of absence of break statement, this will print 10 and 20.
Does anyone else think this feels like an error in the language?
Not every language allows fall-through in switch statement. Wikipedia has a brief section on it.
The C (C, C++, Objective-C) family allows fall through by default
The Pascal family does not
Perl does not by default but you can ask by for it by including continue keyword
C# (which is closer to Java than C) requires a break to end every case block but allow you to group empty blocks together:
Swift does not allow fall through and has a powerful pattern-matching system, in addition to requiring the switch to be exhaustive.
There's wide variety of requirements on the switch statements. Not every language is the same! A couple small examples:
// C#
switch (i) {
case 1:
case 2:
// you can group empty case blocks together
break; // but must end with break
case 3:
// do something else
break;
}
// Swift
switch i {
case 1: // match 1
case 2,3: // match 2 or 3
case 4...10: // match 4 to 10 (inclusive)
case let n where n % 2 == 0: // match an even number and assign it to n
default: // must be exhaustive
}
See also: Appropriate uses of fall-through switch statements

switch vs if-else branching control structure in Node.JS

Which one is good to use when there is a large number of branching flow in Node.JS Program.
switch
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
OR
if-else
if (condition1)
{
execute code block 1
}
else if(condition2)
{
execute code block 2
}
else
{
code to be executed if n is different from condition1 and condition2
}
For just a few items, the difference is small. If you have many items you should definitely use a switch. It give better performance than if-else.
If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if-else where the last item takes much more time to reach as it has to evaluate every previous condition first..
switch(n)
{
case 1,3,4:
execute code block 1
break;
case 2,5,9,10:
execute code block 2
break;
default:
code to be executed if n is different from first 2 cases.
}
To write down the if...else if...else steps for the above case, you will have to write the 'OR (||)' condition-statement and repeat the variable 'n' in the statement, Where as switch cases can be separated by just a comma ','. Thus switch is more readable for such a case.

To ternary or not to ternary? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm personally an advocate of the ternary operator: () ? :
I do realize that it has its place, but I have come across many programmers that are completely against ever using it, and some that use it too often.
What are your feelings on it? What interesting code have you seen using it?
Use it for simple expressions only:
int a = (b > 10) ? c : d;
Don't chain or nest ternary operators as it hard to read and confusing:
int a = b > 10 ? c < 20 ? 50 : 80 : e == 2 ? 4 : 8;
Moreover, when using ternary operator, consider formatting the code in a way that improves readability:
int a = (b > 10) ? some_value
: another_value;
It makes debugging slightly more difficult since you can not place breakpoints on each of the sub expressions. I use it rarely.
I love them, especially in type-safe languages.
I don't see how this:
int count = (condition) ? 1 : 0;
is any harder than this:
int count;
if (condition)
{
count = 1;
}
else
{
count = 0;
}
I'd argue that ternary operators make everything less complex and more neat than the alternative.
Chained I'm fine with - nested, not so much.
I tend to use them more in C simply because they're an if statement that has value, so it cuts down on unnecessary repetition or variables:
x = (y < 100) ? "dog" :
(y < 150) ? "cat" :
(y < 300) ? "bar" : "baz";
rather than
if (y < 100) { x = "dog"; }
else if (y < 150) { x = "cat"; }
else if (y < 300) { x = "bar"; }
else { x = "baz"; }
In assignments like this, I find it's less to refactor, and clearer.
When I'm working in ruby on the other hand, I'm more likely to use if...else...end because it's an expression too.
x = if (y < 100) then "dog"
elif (y < 150) then "cat"
elif (y < 300) then "bar"
else "baz"
end
(Although, admittedly, for something this simple, I might just use the ternary operator anyway.)
The ternary ?: operator is merely a functional equivalent of the procedural if construct. So as long as you are not using nested ?: expressions, the arguments for/against the functional representation of any operation applies here. But nesting ternary operations can result in code that is downright confusing (exercise for the reader: try writing a parser that will handle nested ternary conditionals and you will appreciate their complexity).
But there are plenty of situations where conservative use of the ?: operator can result in code that is actually easier to read than otherwise. For example:
int compareTo(Object object) {
if((isLessThan(object) && reverseOrder) || (isGreaterThan(object) && !reverseOrder)) {
return 1;
if((isLessThan(object) && !reverseOrder) || (isGreaterThan(object) && reverseOrder)) {
return -1;
else
return 0;
}
Now compare that with this:
int compareTo(Object object) {
if(isLessThan(object))
return reverseOrder ? 1 : -1;
else(isGreaterThan(object))
return reverseOrder ? -1 : 1;
else
return 0;
}
As the code is more compact, there is less syntactic noise, and by using the ternary operator judiciously (that is only in relation with the reverseOrder property) the end result isn't particularly terse.
It's a question of style, really; the subconscious rules I tend to follow are:
Only evaluate 1 expression - so foo = (bar > baz) ? true : false, but NOT foo = (bar > baz && lotto && someArray.Contains(someValue)) ? true : false
If I'm using it for display logic, e.g. <%= (foo) ? "Yes" : "No" %>
Only really use it for assignment; never flow logic (so never (foo) ? FooIsTrue(foo) : FooIsALie(foo) ) Flow logic in ternary is itself a lie, ignore that last point.
I like it because it's concise and elegant for simple assignment operations.
Like so many opinion questions, the answer is inevitably: it depends
For something like:
return x ? "Yes" : "No";
I think that is much more concise (and quicker for me to parse) than:
if (x) {
return "Yes";
} else {
return "No";
}
Now if your conditional expression is complex, then the ternary operation is not a good choice. Something like:
x && y && z >= 10 && s.Length == 0 || !foo
is not a good candidate for the ternary operator.
As an aside, if you are a C programmer, GCC actually has an extension that allows you to exclude the if-true portion of the ternary, like this:
/* 'y' is a char * */
const char *x = y ? : "Not set";
Which will set x to y assuming y is not NULL. Good stuff.
In my mind, it only makes sense to use the ternary operator in cases where an expression is needed.
In other cases, it seems like the ternary operator decreases clarity.
I use the ternary operator wherever I can, unless it makes the code extremely hard to read, but then that's usually just an indication that my code could use a little refactoring.
It always puzzles me how some people think the ternary operator is a "hidden" feature or is somewhat mysterious. It's one of the first things I learnt when I start programming in C, and I don't think it decreases readability at all. It's a natural part of the language.
By the measure of cyclomatic complexity, the use of if statements or the ternary operator are equivalent. So by that measure, the answer is no, the complexity would be exactly the same as before.
By other measures such as readability, maintainability, and DRY (don't repeat yourself), either choice may prove better than the other.
I use it quite often in places where I'm constrained to work in a constructor - for example, the new .NET 3.5 LINQ to XML constructs - to define default values when an optional parameter is null.
Contrived example:
var e = new XElement("Something",
param == null ? new XElement("Value", "Default")
: new XElement("Value", param.ToString())
);
or (thanks asterite)
var e = new XElement("Something",
new XElement("Value",
param == null ? "Default"
: param.ToString()
)
);
No matter whether you use the ternary operator or not, making sure your code is readable is the important thing. Any construct can be made unreadable.
I agree with jmulder: it shouldn't be used in place of a if, but it has its place for return expression or inside an expression:
echo "Result: " + n + " meter" + (n != 1 ? "s" : "");
return a == null ? "null" : a;
The former is just an example, and better internationalisation and localisation support of plural should be used!
If you're using the ternary operator for a simple conditional assignment I think it's fine. I've seen it (ab)used to control program flow without even making an assignment, and I think that should be avoided. Use an if statement in these cases.
(Hack of the day)
#define IF(x) x ?
#define ELSE :
Then you can do if-then-else as expression:
int b = IF(condition1) res1
ELSE IF(condition2) res2
ELSE IF(conditions3) res3
ELSE res4;
I think the ternary operator should be used when needed. It is obviously a very subjective choice, but I find that a simple expression (specially as a return expression) is much clearer than a full test. Example in C/C++:
return (a>0)?a:0;
Compared to:
if(a>0) return a;
else return 0;
You also have the case where the solution is between the ternary operator and creating a function. For example in Python:
l = [ i if i > 0 else 0 for i in lst ]
The alternative is:
def cap(value):
if value > 0:
return value
return 0
l = [ cap(i) for i in lst ]
It is needed enough that in Python (as an example), such an idiom could be seen regularly:
l = [ ((i>0 and [i]) or [0])[0] for i in lst ]
this line uses properties of the logical operators in Python: they are lazy and returns the last value computed if it is equal to the final state.
I've seen such beasts like (it was actually much worse since it was isValidDate and checked month and day as well, but I couldn't be bothered trying to remember the whole thing):
isLeapYear =
((yyyy % 400) == 0)
? 1
: ((yyyy % 100) == 0)
? 0
: ((yyyy % 4) == 0)
? 1
: 0;
where, plainly, a series of if-statements would have been better (although this one's still better than the macro version I once saw).
I don't mind it for small things like:
reportedAge = (isFemale && (Age >= 21)) ? 21 + (Age - 21) / 3 : Age;
or even slightly tricky things like:
printf ("Deleted %d file%s\n", n, (n == 1) ? "" : "s");
I like using the operator in debug code to print error values so I don't have to look them up all the time. Usually I do this for debug prints that aren't going to remain once I'm done developing.
int result = do_something();
if( result != 0 )
{
debug_printf("Error while doing something, code %x (%s)\n", result,
result == 7 ? "ERROR_YES" :
result == 8 ? "ERROR_NO" :
result == 9 ? "ERROR_FILE_NOT_FOUND" :
"Unknown");
}
I almost never use the ternary operator, because whenever I do use it, it always makes me think a lot more than I have to later when I try to maintain it.
I like to avoid verbosity, but when it makes the code a lot easier to pick up, I will go for the verbosity.
Consider:
String name = firstName;
if (middleName != null) {
name += " " + middleName;
}
name += " " + lastName;
Now, that is a bit verbose, but I find it a lot more readable than:
String name = firstName + (middleName == null ? "" : " " + middleName)
+ " " + lastName;
Or:
String name = firstName;
name += (middleName == null ? "" : " " + middleName);
name += " " + lastName;
It just seems to compress too much information into too little space, without making it clear what's going on. Every time I saw the ternary operator used, I have always found an alternative that seemed much easier to read... then again, that is an extremely subjective opinion, so if you and your colleagues find ternary very readable, go for it.
I like them. I don't know why, but I feel very cool when I use the ternary expression.
I treat ternary operators a lot like GOTO. They have their place, but they are something which you should usually avoid to make the code easier to understand.
Well, the syntax for it is horrid. I find functional ifs very useful, and they often makes code more readable.
I would suggest making a macro to make it more readable, but I'm sure someone can come up with a horrible edge case (as there always is with C++).
I typically use it in things like this:
before:
if(isheader)
drawtext(x, y, WHITE, string);
else
drawtext(x, y, BLUE, string);
after:
drawtext(x, y, isheader == true ? WHITE : BLUE, string);
As others have pointed out they are nice for short simple conditions. I especially like them for defaults (kind of like the || and or usage in JavaScript and Python), e.g.
int repCount = pRepCountIn ? *pRepCountIn : defaultRepCount;
Another common use is to initialize a reference in C++. Since references have to be declared and initialized in the same statement you can't use an if statement.
SomeType& ref = pInput ? *pInput : somethingElse;
I like Groovy's special case of the ternary operator, called the Elvis operator: ?:
expr ?: default
This code evaluates to expr if it's not null, and default if it is. Technically it's not really a ternary operator, but it's definitely related to it and saves a lot of time/typing.
I recently saw a variation on ternary operators (well, sort of) that make the standard "() ? :" variant seem to be a paragon of clarity:
var Result = [CaseIfFalse, CaseIfTrue][(boolean expression)]
or, to give a more tangible example:
var Name = ['Jane', 'John'][Gender == 'm'];
Mind you, this is JavaScript, so things like that might not be possible in other languages (thankfully).
Only when:
$var = (simple > test ? simple_result_1 : simple_result_2);
KISS.
For simple if cases, I like to use it. Actually it's much easier to read/code for instance as parameters for functions or things like that. Also to avoid the new line I like to keep with all my if/else.
Nesting it would be a big no-no in my book.
So, resuming, for a single if/else I'll use the ternary operator. For other cases, a regular if/else if/else (or switch).
For simple tasks, like assigning a different value depending on a condition, they're great. I wouldn't use them when there are longer expressions depending on the condition though.
If you and your workmates understand what they do and they aren't created in massive groups I think they make the code less complex and easier to read because there is simply less code.
The only time I think ternary operators make code harder to understand is when you have more than three or foyr in one line. Most people don't remember that they are right based precedence and when you have a stack of them it makes reading the code a nightmare.
As so many answers have said, it depends. I find that if the ternary comparison is not visible in a quick scan down the code, then it should not be used.
As a side issue, I might also note that its very existence is actually a bit of an anomaly due to the fact that in C, comparison testing is a statement. In Icon, the if construct (like most of Icon) is actually an expression. So you can do things like:
x[if y > 5 then 5 else y] := "Y"
... which I find much more readable than a ternary comparison operator. :-)
There was a discussion recently about the possibility of adding the ?: operator to Icon, but several people correctly pointed out that there was absolutely no need because of the way if works.
Which means that if you could do that in C (or any of the other languages that have the ternary operator), then you wouldn't, in fact, need the ternary operator at all.

Resources