What is the difference between IF-ELSE and SWITCH? - language-agnostic

Can someone please explain this to me?

They are pretty similar but each has a few special features.
switch
switch is usually more compact than lots of nested if else and therefore, more readable
If you omit the break between two switch cases, you can fall through to the next case in many C-like languages. With if else you'd need a goto (which is not very nice to your readers ... if the language supports goto at all).
In most languages, switch only accepts primitive types as key and constants as cases. This means it can be optimized by the compiler using a jump table which is very fast.
It is not really clear how to format switch correctly. Semantically, the cases are jump targets (like labels for goto) which should be flush left. Things get worse when you have curly braces:
case XXX: {
} break;
Or should the braces go into lines of their own? Should the closing brace go behind the break? How unreadable would that be? etc.
In many languages, switch only accepts only some data types.
if-else
if allows complex expressions in the condition while switch wants a constant
You can't accidentally forget the break between ifs but you can forget the else (especially during cut'n'paste)
it accepts all data types.

The main difference is that switch despatches immediately to the case concerned, typically via an indexed jump, rather than having to evaluate all the conditions that would be required in an if-else chain, which means that code at the end of the chain is reached more slowly than code at the beginning.
That in turn imposes some restrictions on the switch statement that the if-else chain doesn't have: it can't handle all datatypes, and all the case values have to be constant.

IF else - IT is used for taking a decisions
Switch statement - It is used to test the value of the given variable against a list of case value .

Differences Between if-else and switch
Expression inside if statement decide whether to execute the statements inside if block or under else block. On the other hand, expression inside switch statement decide which case to execute.
If-esle statement checks for equality as well as for logical expression . On the other hand, switch checks only for equality.
The if statement evaluates integer, character, pointer or floating-point type or boolean type. On the other hand, switch statement evaluates only character or a integer datatype.
Sequence of execution is like either statement under if block will execute or statements under else block statement will execute. On the other hand the expression in switch statement decide which case to execute and if you do not apply a break statement after each case it will execute till the end of switch statement.
If expression inside if turn outs to be false, statement inside else block will be executed. If expression inside switch statement turn out to be false then default statements is executed.
It is difficult to edit if-else statements as it is tedious to trace where the correction is required. On the other hand it is easy to edit switch statements as they are easy to trace.
in one word we can say
switch acts a little bit faster than if else statement!!!

The difference between Switch and if-else statement is below:
This is the general syntax of if-else ladder:
if (condition1) { //Body of if }
else if (condition2) { //Body of if }
else if (condition3) { //Body of if }
else { //default if all conditions return false }
And this is the general syntax for switch:
switch ( variable )
{
case <variable value1>: //Do Something
break;
case <variable value2>://Do Something
break;
default: //Do Something
break;
}
The if-else ladder is of type strict condition check,
while switch is of type jump value catching.
Advantages of switch over if-else ladder:
A switch statement works much faster than equivalent if-else ladder. It is because compiler generates a jump table for a switch during compilation. Consequently, during execution, instead of checking which case is satisfied, it only decides which case has to be executed.
It is more readable and in compare to if-else statements.

A Clear difference:
The if...else statement checks whether the conditions in the parenthesis evaluates to true or false
The switch statement checks if the equality of the value in the parenthesis against the value of the case keyword evaluates to true.
Example
var a = 'hello'
Example - if...else
if(a == 'hello') {
print('right!')
} else if (a == 'hi')
print('left!')
} else {
print('wrong!')
}
Example - Switch
switch(a) {
case 'hello': // a == 'hello'
print('right!')
break // You should add this
case 'hi': // a == 'hi'
print('left!')
break
default: // this executes if no equality was met in the values above.
print('wrong!')
}
// If you are not sure of either of the parenthesis value or the
// case value or you want to make more complex conditioning, you can use `true`:
var age = 18:
switch(true) {
case age < "18": // 18 < 18 == false
print("under age!");
break;
case age == 18: // 18 == 18 == true
print("right age!");
break;
default:
print("18+!");
}

i think that main difference is that in if-else blocks we can test conditions.but does not go exactly in same way in switch

Related

what are `switch` statements for?

Switch statements: I know what they do - I use them so many times, as per convention normally when I want to do different stuff based on the value of an Enum, but now it just hit me: Why are we using it? What was its original purpose? I mean, this:
switch(myVar) {
case Foo:
doSomething();
break;
case Bar:
doSomethingElse();
break;
default:
justAnotherThing();
break;
}
Has the exact same behaviour as:
if(myVar == Foo) {
doSomething()
}else if(myVar == Bar) {
doSomethingElse();
}else {
justAnotherThing();
}
Plus if's lets you make inequality comparisons (>, <, !=) if you need it. The only case that I may find a switch more useful is when you don't use the break statement inside: but this happens not too often and I find it terrible on code-quality.
I really can't find any benefit of using switch over if... So why was it defined for?
Some languages allow inequality comparisons in switch statements as well, e.g. Visual Basic:
Select Case x
Case < 5
// ...
Case 7
// ...
Case 10 To 15
// ...
Case Else
// ...
End Select
Basically, yes, the switch can often be written as an if/else if ladder, with the distinction that switch compares one value against a number of comparison values, if/else if can do anything in every single branch. But even that isn't the case in all languages, e.g. in PowerShell a switch can do plenty of things that you usually have to use if for:
switch -Regex ($x) {
'^\d+$' {'Number'}
}
or
switch ($x) {
{ $_ is [int] -or $_ is [double] } {'Number'}
{ $_ is [string] } {'Text'}
}
Generally, however, switch is easier to read for the common case of comparing a single value against a finite set of options. Furthermore, it enables the compiler to do certain optimizations which are harder to analyse on if/else if, such as using binary search to determine the correct case instead of linear search, or even using a jump table or arithmetic. E.g. the following switch
switch (x) {
case 0:
// Do something with 0
break;
case 1:
// Do something with 1
break;
case 2:
// Do something with 2
break;
...
}
could be compiled into the equivalent of
Action[] actions = {
() => { /* Do something with 0 */ },
() => { /* Do something with 1 */ },
() => { /* Do something with 2 */ },
...
};
if (x >=0 && x <= n) {
actions[x]();
}
The simplicity and limitations of switch are helpful in this case for an optimizing compiler because there's much less to analyse to determine what the overall structure is trying to do.
There are other features (sometimes maybe of dubious value), such as Duff's device, or being able to fall through to other cases (or goto arbitrary other cases, which, e.g. C# allows).
You may just as well ask the question why we have if statements and loops instead of just using goto. Yes, structured programming constructs are, taken one by one, strictly inferior in what they can express, compared to the more general construct. But they are more readable, make the intent clearer, and tend to be safer and easier to maintain.
switch is a pretty low-level statement, in the sense that the code in the case statements is compiled into a continuous block of instructions in memory which is simply conditionally jumped into (depends on the language in question of course, modern high-level languages may behave quite different under the hood). That's also why you have the fall-through behaviour, once a starting address is determined simply all following instructions are executed unless broken out of.
So initially it was a very natural way to jump over or into a block of instructions. Many languages have adopted the switch statement, many likely due to familiarity, but many likely also because it is indeed rather readable for certain cases, e.g.:
switch (someComplicatedCalculation($foo, $bar)) {
case CONSTANT_A:
...
case CONSTANT_B:
...
...
}
That's a pretty succinct way to express this, especially if you're maybe also depending on the fall-through behaviour.
Of course, other languages have never adopted switch, e.g. Python, and require the use of if..elif..else instead. In the end you can write similar code using either language construct, it's up to you.

Returning values in Elixir?

I've recently decided to learn Elixir. Coming from a C++/Java/JavaScript background I've been having a lot of trouble grasping the basics. This might sound stupid but how would return statements work in Elixir? I've looked around and it seems as though it's just the last line of a function i.e.
def Hello do
"Hello World!"
end
Would this function return "Hello World!", is there another way to do a return? Also, how would you return early? in JavaScript we could write something like this to find if an array has a certain value in it:
function foo(a){
for(var i = 0;i<a.length;i++){
if(a[i] == "22"){
return true;
}
}
return false;
}
How would that work in Elixir?
Elixir has no 'break out' keyword that would be equivalent to the 'return' keyword in other languages.
Typically what you would do is re-structure your code so the last statement executed is the return value.
Below is an idiomatic way in elixir to perform the equivalent of your code test, assuming you meant 'a' as something that behaves kind of array like in your initial example:
def is_there_a_22(a) do
Enum.any?(a, fn(item) -> item == "22" end.)
end
What's actually going on here is we're restructuring our thinking a little bit. Instead of the procedural approach, where we'd search through the array and return early if we find what we were looking for, we're going to ask what you are really after in the code snippet:
"Does this array have a 22 anywhere?"
We are then going to use the elixir Enum library to run through the array for us, and provide the any? function with a test which will tell us if anything matches the criteria we cared about.
While this is a case that is easily solved with enumeration, I think it's possible the heart of your question applies more to things such as the 'bouncer pattern' used in procedural methods. For example, if I meet certain criteria in a method, return right away. A good example of this would be a method that returns false if the thing you're going to do work on is null:
function is_my_property_true(obj) {
if (obj == null) {
return false;
}
// .....lots of code....
return some_result_from_obj;
}
The only way to really accomplish this in elixir is to put the guard up front and factor out a method:
def test_property_val_from_obj(obj) do
# ...a bunch of code about to get the property
# want and see if it is true
end
def is_my_property_true(obj) do
case obj do
nil -> false
_ -> test_property_value_from_obj(obj)
end
end
tl;dr - No there isn't an equivalent - you need to structure your code accordingly. On the flip side, this tends to keep your methods small - and your intent clear.
You are correct in that last expression is always returned. Even more - there are no statements in the language - just expressions. Every construct has a value - if, case, etc. There is also no early return. This may seem limiting, but you quickly get used to it.
A normal way to solve your example with Elixir would be to use a higher order function:
def foo(list) do
Enum.any?(list, fn x -> x == "22" end)
end

is there any practical difference between these two if() statements?

Is there any practical (faster/slower, functionality, etc) difference between these two sets of if statements?
1:
var myVar:Boolean;
if (myVar == true)
{
//do stuff
}
//waldo:
if (myVar == false)
{
//do other stuff
}
2:
var myVar:Boolean;
if (myVar == true)
{
//do stuff
}
//waldo:
else
{
//do other stuff
}
This is specifically a question about if() statements for variables that only have two possible values (other than null), like Boolean variables.
These examples are not functionally same. As #Nicolas already mentioned that myVar can be changed in first block and then second if statement will be true. Something like this:
if (myVar == true)
{
//do stuff
myVar = false;
}
if (myVar == false)
{
// now this will be executed
}
This won't happen in the second case.
In first example boolean value is checked twice (i.e. two if statements), but in second one boolean value is checked only once. This gives a slight performance benefit. It won't be much if this is done rarely, but if this code is executed many many time per seconds (e.g. inside enter frame event for hundreds of movie clips) then performance benefit like this can become crucial. For example, if you can save 50 milliseconds per second then that will be 5 percent performance improvement.
In my opinion, second example is more readable.
The main difference is that in the first example, if the value of myVar changes between the two blocks to false, the second statement will still execute. In the second example, even if myVar becomes false after the first block completes, the else clause will not be executed because the associated if clause has already been executed (only one of them will run).
As far as performance and code quality go, you'll usually want to use something like the second example (unless the side effects of the first example are necessary).

Can if statements be implemented as function calls?

One of the stylistic 'conventions' I find slightly irritating in published code, is the use of:
if(condition) {
instead of (my preference):
if (condition) {
A slight difference, and probably an unimportant one, but it occurred to me that the first style might be justified if 'if' statements were implemented as a kind of function call. Then I could stop objecting to it.
Does anyone know of a programming language where an if statement is implemented as a function call, where the argument is a single boolean expression?
EDIT: I realise the blocks following the if() are problematic, and the way I expressed my question was probably too naive, but I'm encouraged by the answers so far.
tcl is one language which implements if as a regular in built function/command which takes two parameters ; condition and the code block to execute
if {$vbl == 1} { puts "vbl is one" }
http://tmml.sourceforge.net/doc/tcl/if.html
In fact, all language constructs in tcl (for loop , while loop etc.) are implemented as commands/functions.
It's impossible for it to have a single argument since it has to decide which code path to follow, which would have to be done outside of said function. It would need at least two arguments, but three would allow an "else" condition.
Lisp's if has exactly the same syntax as any other macro in the language (it's not quite exactly a function, but the difference is minimal): (if cond then else)
Both the 'then' and 'else' clauses are left unevaluated unless the condition selects them.
In Smalltalk, an if statement is kind of a function call -- sort of, in (of course) a completely object oriented way, so it's really a method not a free function. I'm not sure how it would affect your thinking on syntax though, since the syntax is completely different, looking like:
someBoolean
ifTrue: [ do_something ]
ifFalse: [ do_something_else ]
Given that this doesn't contain any parentheses at all, you can probably interpret it as proving whatever you wanted to believe. :-)
If the if function is to be a regular function, then it can't just take the condition, it needs as its parameters the block of code to run depending on whether the condition evaluates to true or not.
A prototype for a function like that in C++ might be something along the lines of
void custom_if(bool cond, void (*block)());
This function can either call the block function, or not, depending on cond.
In some functional languages things are much easier. In Haskell, a simple function like:
if' True a _ = a
if' _ _ b = b
allows you to write code like this:
if' (1 == 1)
(putStrLn "Here")
(putStrLn "There")
which will always print Here.
I don't know of any languages where if(condition) is implemented as a regular function call, but Perl implements try { } catch { } etc.. {} as function calls.

True until disproven or false until proven?

I've noticed something about my coding that is slightly undefined. Say we have a two dimension array, a matrix or a table and we are looking through it to check if a property is true for every row or nested dimension.
Say I have a boolean flag that is to be used to check if a property is true or false. My options are to:
Initialize it to true and check each cell until proven false. This
gives it a wrong name until the code
is completely executed.
Start on false and check each row until proven true. Only if all rows are true will the data be correct. What is the cleanest way to do this, without a counter?
I've always done 1 without thinking but today it got me wondering. What about 2?
Depends on which one dumps you out of the loop first, IMHO.
For example, with an OR situation, I'd default to false, and as soon as you get a TRUE, return the result, otherwise return the default as the loop falls through.
For an AND situation, I'd do the opposite.
They actually both amount to the same thing and since you say "check if a property is true for every row or nested dimension", I believe the first method is easier to read and perhaps slightly faster.
You shouldn't try to read the value of the flag until the code is completely executed anyway, because the check isn't finished. If you're running asynchronous code, you should guard against accessing the value while it is unstable.
Both methods "give a wrong name" until the code is executed. 1 gives false positives and 2 gives false negatives. I'm not sure what you're trying to avoid by saying this - if you can get the "correct" value before fully running your code, you didn't have run your code in the first place.
How to implement each without a counter (if you don't have a foreach syntax in your language, use the appropriate enumerator->next loop syntax):
1:
bool flag = true;
foreach(item in array)
{
if(!check(item))
{
flag = false;
break;
}
}
2:
bool flag = false;
foreach(item in array)
{
if(!check(item))
{
break;
}
else if(item.IsLast())
{
flag = true;
}
}
Go with the first option. An algorithm always has preconditions, postconditions and invariants. If your invariant is "bool x is true iff all rows from 0-currentN have a positve property", then everything is fine.
Don't make your algorithm more complex just to make the full program-state valid per row-iteration. Refactor the method, extract it, and make it "atomic" with your languages mechanics (Java: synchronized).
Personally I just throw the whole loop into a somewhat reusable method/function called isPropertyAlwaysTrue(property, array[][]) and have it return a false directly if it finds that it finds a case where it's not true.
The inversion of logic, by the way, does not get you out of there any quicker. For instance, if you want the first non-true case, saying areAnyFalse or areAllTrue will have an inverted output, but will have to test the exact same cases.
This is also the case with areAnyTrue and areAllFalse--different words for the exact same algorithm (return as soon as you find a true).
You cannot compare areAnyFalse with areAnyTrue because they are testing for a completely different situation.
Make the property name something like isThisTrue. Then it's answered "yes" or "no" but it's always meaningful.
In Ruby and Scheme you can use a question mark in the name: isThisTrue?. In a lot of other languages, there is a convention of puttng "p" for "predicate" on the name -- null-p for a test returning true or false, in LISP.
I agree with Will Hartung.
If you are worried about (1) then just choose a better name for your boolean. IsNotSomething instead of IsSomething.