C: handling case...else - c

What is the correct way to put an else clause in a switch statement? For example, instead of:
switch (input) {
case (1):
printf("yes!");
break
case (0):
printf("no!");
break;
default:
printf("invalid!");
}
To do something along the lines of (if possible):
switch (input) {
case (1):
printf("yes!");
case (0):
printf("no!");
else:
printf("invalid!");
}
I'm simply asking if there is a short-cut to not have to add a break after every case statement to act as-if it were the else part of an if statement.

The correct way is using default. Also ,you don't have to use break for non-default cases, only if you don't want execution to fall into the next case.

Related

Angularjs switch statement

I am fetching few values from my backend and assigning then to my scope variables in angular controller. for one of the variables I get the values between 1 till 7 and depending on the which number it is I want to do something like following:
.success(function(response){
$scope.initial_data=response;
angular.forEach($scope.initial_data, function(item){
$scope.exercise_id=item.exercise_type;
alert($scope.exercise_id) // This gives me either 1 or any number till 7
switch($scope.exercise_id){
case '1':
alert("1");
break;
case '2':
alert("2");
break;
default:
alert("Default");
}
However, this piece of code for switch statement always alerts gives me Default. What am I doing wrong?

angularjs $event get the same code for uppercase and lowercase for a key

i'm struggling to create hotkeys using angularjs $event. i need to simplify the codes for uppercase and lowercase. however i viewed from the console.log($event) they have different keyCode.
p is 112
P is 80
HTML:
<body ng-app="pointofsale" ng-controller="PointofSaleCtrl" ng-keypress="hotKeyEvent($event)">
Javascript:
$scope.hotKeyEvent = function(data){
console.log(data);
switch(data.keyCode){
case 112: // p
break;
case 80: // P
break;
default:
console.log('No key associated')
}
}
What am i missing here? i don't want to create two conditions for the same character but different case.
Appreciate any help, Thanks!
You could simplify your switch by grouping the case statements
like this:
switch(data.keyCode){
case 112: // p
case 80: // P
break;
default:
console.log('No key associated')
}
It's known as falling through - essentially, anything matched will continue to run until a break is hit.
Makes maintenance quite a bit easier too.

How to break outer loops from inner structures that respond break (loops/switch)

How to I break an outer loop from within an nested structure that responds to the break statement in Swift?
For example:
while someCondition {
if someOtherCondition {
switch (someValue) {
case 0: // do something
case 1: // exit loop
case 2...5: // do something else
default: break
}
} else {
someCondition = false
}
}
The break will only get me out of the switch, and in Swift, it has to be used as empty cases are not allowed. How can I entirely exit the loop from within the switch?
Swift allows for labeled statements. Using a labeled statement, you can specify which which control structure you want to break from no matter how deeply you nest your loops (although, generally, less nesting is better from a readability standpoint). This also works for continue.
Example:
outerLoop: while someCondition {
if someOtherCondition {
switch (someValue) {
case 0: // do something
case 1: break outerLoop // exit loop
case 2...5: // do something else
default: break
}
} else {
someCondition = false
}
}
Label the loop as outerLoop and whenever needed user break Label: i.e. break outerLoop in our case.
outerLoop: for indexValue in 0..<arr.count-1 {
if arr[indexValue] > arr[indexValue+1] {
break outerLoop
}
}

Case cannot fall through from one case label to another

Hi for some reason the break at the end of the "AndGroup" case is unreachable. I have tried to fix this with a goto and even moving the "return true" without result. Can anyone help me out?
switch (dependant[0])
{
case "AndGroup":
string[] sAndItems =
dependant[10].Split(
new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
foreach (string sAndItem in sAndItems)
{
if (SC_Product.Dependancies.ContainsKey(sAndItem))
{
if (!SC_Product.Dependancies[sAndItem].DependantInstalled)
return false;
}
}
return true;
break;
case "Windows":
The break is unreachable because you have already exited via return true - there's no possible code branch by which the break can be executed.
Stuart is right "there's no possible code branch by which the break can be executed" , you may set a field but don't use return.

c ideas on shrinking this function?

I have this huge switch case with nested switch case statements in it that I was wondering if anyone had any ideas on how to clean up?
switch (datatype) {
case STR:
{
switch(operation)
{
case EQUALS:
{
/* perform str compare */
}
case NOTEQUALS:
{
}
case LT:
{
}
case GT:
{
}
case GTE:
{
}
case LTE:
{
}
default:
break;
}
break;
}
case VER:
{
switch(operation)
{
case EQUALS:
{
/* perform version compare */
}
case NOTEQUALS:
{
}
case LT:
{
}
case GT:
{
}
case GTE:
{
}
case LTE:
{
}
default:
break;
}
break;
}
case INT:
{
/* same */
}
case FLOAT:
{
/* same */
}
/* ... more types ... */
/* ... .......... ... */
default:
break;
}
If the values for the operation are contiguous, you could make a table of function pointers. In fact you could make a 2D table of function pointers with a separate function to handle each operation/type combination. e.g
// do some range checking on input params
// invoke the handler
handlers[datatype][operation]();
Create some tables (arrays) with pointers to functions in it. You can then look up func[STR][EQUALS] to make the appropriate call. The call would end up looking like this...
Func[datatype][operation]();
You could try the command pattern.
The NOTEQUALS case can always be written in terms of the EQUALS case; similarly GTE in terms of LT and LTE in terms of GE. So make the outer switch in terms of the operation, and only three of those six cases will need to switch on the datatype.
You could use a big array of function pointers and then call the relevant function based upon indexing to the correct function pointer in the array.
have you considered creatively using a series of function pointers and storing them in a struct?
do it right and you can mimic objects and do something this like:
bool someArbitraryFunction (dataType aDatatype, operations anOperation)
{
someUnknownStruct.datatype = aDatatype;
someUnknownStruct.operation = anOperation;
return someUnknownStruct->doMath(1,2);
}
and then you can put all the needed math functions, enums, and structs in a header file somewhere.
cleans up the "meat" of the code, and makes the math portable (just import it wherever you need it).
Assuming your cases can all return a simple boolean value, all six logic cases can be rewritten in terms of LT and EQUALS, like follows:
switch(operation) {
case EQUALS:
return isEquals();
case NOTEQUALS:
return !isEquals();
case LT:
return isLT();
case GT:
return !isLT() && !isEquals();
case GTE:
return !isLT();
case LTE:
reutrn isLT() || isEquals();
default:
break;
}
This would only require you to write the logic for isLT() and isEquals(), which would do the switching on datatype when necessary. This eliminates a significant amount of unnecessary code duplication, yet doesn't sacrifice a lot of legibility.
This can be combined with function pointers as Stephen Doyle and rikh already suggested, which would eliminate the switch() statement entirely.

Resources