break out of switch case - switch-statement

Wondering if I can break out of my case if the break is in an if statement, or if the break will just exit the if and not the case. I only want to fallthrough to the next case if the else is executed. Thanks
case PS_STARTED:
readyForPwrDn_b = appReadyForPwrDn_b;
if (!readyForPwrDn_b)
{
break;
}
else
{
CurrentPowerState_e = PS_COMPLETE;
}
//fallthrough
case PS_COMPLETE:

There's no such thing as breaking out of an if. break applies only to switch and to loops in all the programming languages I'm familiar with.
PHP:
break ends execution of the current for, foreach, while, do-while or switch structure.
Javascript:
The break statement terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
C++:
The break statement is used with the conditional switch statement and with the do, for, and while loop statements.
However, these all apply to non-labeled break statements. In some languages you can write:
myIf:
if (!readyForPwrDn_b) {
break myIf;
} else {
CurrentPowerState_e = PS_COMPLETE;
}
This would just break out of the if.

if (condition)
{
//Do your thing
if (breakOutCondition)
return;
//Continue your code
}
This if statement would work, but there is an easy, clean way of getting out of a loop like this. You could use a goto to break this variable scope and it will make it loop a hell of alot cleaner. WARNING: goto is sometimes dreaded because it is essentially a break in disguise.
if (breakoutcondition)
{
...
goto foo;
...
}
foo:
//Continue here

Related

What is the equivalent of 'pass' from Python?

I want to check if the result from a request is having any issue. I categorize it into two: i) server error, ii) something else that is not a success. The third category is, result actually being a success. However, in the third category, I don't want to do anything.
So, my desirable code is:
if res.status().is_server_error() {
panic!("server error!");
} else if !(res.status.is_success()){
panic!("Something else happened. Status: {:?}", res.status());
} else{
pass;
}
I am aware of other ways to achieve this result: using match, ifs instead of if else if. But I wanted to learn what is the corresponding keyword of pass, like we have in Python. My aim is: if result is successful, just move along, if not, there are two ways to handle that panic.
Behold!
if predicate {
do_things();
} else {
// pass
}
Or even better
if predicate {
do_things();
} // pass
Or as I’ve recently taken to calling it the implicit + pass system
if predicate {
do_things();
}
In all seriousness there is no pass and no need for a pass in rust. As for why it exists in python, check out this answer
Python needs pass because it uses indentation-based blocks, so it requires some syntax to "do nothing". For example, this would be a syntax error in a Python program:
# syntax error - function definition cannot be empty
def ignore(_doc):
# do nothing
count = process_docs(docs, ignore) # just count the docs
The ignore function has to contain a block, which in turn must contain at least one statement. We could insert a dummy statement like None, but Python provides pass which compiles to nothing and signals the intention (to do nothing) to the human reader.
This is not needed in Rust because Rust uses braces for blocks, so one can always create an empty block simply using {}:
// no error - empty blocks are fine
fn ignore(_doc: &Document) {
// do nothing
}
let count = process_docs(docs, ignore); // just count the docs
Of course, in both idiomatic Python and Rust, one would use a closure for something as simple as the above ignore function, but there are still situations where pass and empty blocks are genuinely useful.

Groovy break out of outer switch from nested switch (not in loop)?

switch statements in Groovy are infinitely more flexible, powerful and applicable than in Java. For this reason I've just found myself wanting to use a nested switch for the first time in Groovy.
With this:
outerSwitch:
switch( var1 ){
case 'x':
...
break
case 'y':
switch( var2 ){
case 'a':
// something
break outerSwitch
...
}
...
}
... I get a horrid message from the Groovy compiler saying "Groovy: the break statement with named label is only allowed inside loops". I don't know whether this is the same with Java.
There is an obvious silly workaround: you enclose your outer switch with a while( true ), apply the outerSwitch label to that, and put a break statement at the end of your outer switch.
Or you could do a for( int i = 0; i < 1; i++ ) ... or use a Groovy-er idiom for the same thing, I forget what all the options are... although having tried
outerSwitch:
1.times{
switch( var1 ){
...
}
... I find that the Groovy compiler gives the same nasty message. So you can't fool it with a closure, seemingly.
Is there anything in the Groovy toolkits and boxes of tricks which lets you jump out of the outer switch from the nested switch more sensibly?
The trouble being, I suppose, that when you break from a case block you don't do so with a value... if you could go break true or break 'fiddle-de-dee' there'd be obvious ways to solve this.
An obvious workaround is that you can precede your nested switch with def breakouter = false and then change that as applicable in the case block. I'd just hope that Groovy would provide something more elegant...
Not sure about the break behavior but if refactoring your switch statement is an option, perhaps the following could work:
def var1 = "y"
def var2 = "a"
switch ([var1, var2]) {
case { it.first() == "x"}:
println "var1 == 'x'"
break
case [['y', 'a']]:
println "var1 == 'y', var2 == 'a'"
break
default:
println "something else"
}
where the first case condition is a closure which will execute the case if it returns true and the second is a list of lists which will execute the case if the outer list contains the value.
This code essentially replicates the functionality in your original code snippet but with a flat switch structure. Breaking with labels, even if it worked, is in my mind not a good pattern.
Output:
~> groovy test.groovy
var1 == 'y', var2 == 'a'

C# difference between else if and if

What is the difference between if and else if in C#? For example if i write
if (x==5){
do something
}
And
else if (x==5){
do something
}
Are they totally same… so ? What is the difference?
**IF** you are confused
read the c# spec
**ELSE IF** you are kind of confused
read some books
**ELSE**
everything should be OK.
Courtesy: https://stackoverflow.com/a/1445365/5352399
Jokes are apart, usually an if statement follows this sort of structure:
if (condition)
{
// executed only if "condition" is true
}
else if (other condition)
{
// executed only if "condition" was false and "other condition" is true
}
else
{
// executed only if both "condition" and "other condition" were false
}
The if portion is the only block that is absolutely mandatory. else if allows you to say "ok, if the previous condition was not true, then if this condition is true...". The else says "if none of the conditions above were true..."
You can have multiple else if blocks, but only one if block and only one (or zero) else blocks.
Answer reference: https://stackoverflow.com/a/1439915/5352399
Please read about C# control statements that will give you comprehensive idea.
They aren't the same.
if (true)
DoSomething();
if (true)
DoSomething();
Versus
if (true)
DoSomething();
else if (true)
DoSomething();
The first example does something twice; the second does something only once.
Use else when you don't want multiple cases to be hit.
This is a little tricky, if you use plugins like resharper and you try to write a if sentence preceding of else if sentences, resharper will tell you that the 'else' in 'else if' sentence is redundant and will refactor your code to only if sentences.
Performance issue? or we really don't know how is working c# at this days?

How to break out of a do-while style loop in Rust?

Rust allows a kind of do-while loop eg:
So the C style:
do {
something();
} while (test());
Can be written in Rust as:
while {
something();
test()
}{}
However there is a problem using break in this case:
So this C style:
do {
if (something()) {
break;
}
} while (test());
Can't be written in Rust as:
while {
if (something()) {
break;
}
test()
}{}
Fails to compile with cannot break outside of a loop.
Is there a way to break out of this form of while loop?
Note 1) the reason to use:do {...} while test() flow control instead ofwhile test() {...} is in this case test() will be false when entering the loop initially.
Note 2) When using while {...} flow control: calling continue in the body of the code will skip the break check at the end.
See related question: How to wrap a do-while style loop in a macro, maintaining 'continue' flow control?
As mentioned in the comments, it is important to understand how this pattern works. It is not a special form of while, it simply abuses the loop test to do things normally done in the body. Since break and continue don't belong in the loop test (unless the loop is part of another loop, in which case they will compile, but break/continue the outer loop), Rust rejects them.
A straightforward way to emulate break with the above pattern is by moving the test code to a closure from which one can exit with return:
while (|| {
if something() {
return false // break
}
test()
})() {}
continue can be emulated the same way, simply by returning true from the closure.
It would probably possible to make the intention clearer if this were expressed as a macro.
You are overthinking this.
Let's build a truth table:
+-------------+--------+--------+
| something() | test() | Result |
+-------------+--------+--------+
| true | true | stop |
+-------------+--------+--------+
| true | false | stop |
+-------------+--------+--------+
| false | true | go on |
+-------------+--------+--------+
| false | false | stop |
+-------------+--------+--------+
Thus, this can be written as:
while !something() && test {}
There is no need for a break.
A valid solution close to your proposition could be:
while {
// bloc
test()
} {
// break conditions belonging here
if (something()) {
break;
}
}
Some remarks:
The first bracket has to be an expression, Rust allows the user to write statements before it and the whole bloc with test() is considered as an expression but there are some limitations as you have pointed out
A well built loop generally avoids break and continue statements, this solution has the advantage to separates the loop-flow logic in the first bracket from the added control logic exceptionally used in the second bracket as it were parameters of the loop outside of it
this time something() is called after test(), it means that it won't be able to break the first iteration of the loop
With rust you can label a loop when you declare it and use the label to break the loop later:
'mylabel: loop {
something();
if test() { break 'mylabel; }
}

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.

Resources