It’s just what your error say!!break
statement has to be within the body of a loop
, if
or switch-case
and takes the control out of that block.This is what you should use here instead of break if you want to end the program at that point:
exit(0); //0 means successful termination, non-zero value means otherwise.
I am afraid your program needs an overhaul if you want the whole thing to repeat again.The logic is faulty.Let me check…
Edit Well,here’s your full working program.I am sure you will understand the changes made.Else tell your confusions (if any) in a comment.Here’s a brief explanation of the changes:
Th return
statements in your prompt_contineu()
function needed a little change,the getchar()
there was not needed at all, there was no condition in the while
loop in the main()
function and its body was not well defined within {}
, and last but not the least, the prompt_continue()
function needed to be invoked within the while
loop to get the job done.I hope you can see what the continue
statement does. By the way this evil program said I am FRIGGIN OLD
#include <stdio.h>
#include <string.h>
static int prompt_continue (const char *prompt)
{
printf("%s", prompt);
char answer[5];
if (scanf("%1s", answer) != 1)
return 0;
if (answer[0] == 'y' || answer[0] == 'Y')
{
return 2;
if (answer[0] == 'n' || answer[0] == 'N')
return 3;
}
return 0;
}
int main(void)
{
/*Creates a simple program using if else example. */
int age;
while (1)
{
printf("Welcome, this program is designed for if else statements.\n");
printf("Please enter your age.\n");
scanf (" %d", &age); /*Enters age.*/
if (age < 18)
printf("You are young!\n");
else if (age > 18)
printf("Ah you're old!\n");
printf(" Woot.\n");
if(prompt_continue("Do you want to try again? Y/N")==3)
break;
else
continue;
}
return 0;
}
I am getting this error in my C code. I don’t know what I am doing wrong. If I comment this code my program works. This piece of code is inside int main().
if(argc!=2 && strcmp(argv[0],"selection-sort")==0 && strcmp(argv[1],"input.txt")==0 && strcmp(argv[2],"output.txt")==0)
{
printf("The command line arguments are correct.n");
}
else
{
printf("The command line arguments are wrong.I am exiting.n");
break;
}
paldepind
4,5603 gold badges30 silver badges35 bronze badges
asked Aug 22, 2012 at 19:37
4
The way it looks I think you’re not in a loop but just checking args in main. You probably want something like return 1
or exit(1)
instead of the break.
answered Aug 22, 2012 at 19:38
cnicutarcnicutar
176k25 gold badges358 silver badges389 bronze badges
5
First of all make sure you are including the needed header files:
#include <stdio.h>
#include <stdlib.h>
The break command is used for exiting loops, you are not in a loop you are just in an else statement, you have nothing to break from. The code flow executes normally after passing that else statement. If you want to exit the program in that else statement you could do something like this:
else
{
printf("The command line arguments are wrong.I am exiting.n");
return 1; //exit program with status 1 to indicate a non normal exit
}
Or if you want to continue the program after displaying that message you could just do this:
else printf("The command line arguments are wrong.I am exiting.n");
//more code here
You only use break in loops like so:
while(foo) //while foo is true
{
break; //exit the loop
}
answered Aug 22, 2012 at 19:42
Keith MillerKeith Miller
1,3371 gold badge16 silver badges32 bronze badges
The error message in the title says it all: break
can only be used to exit a loop or prevent a case from falling through. MSDN quote:
The break statement terminates the execution of the nearest enclosing
do, for, switch, or while statement in which it appears.
To leave a function use return
.
answered Aug 22, 2012 at 19:40
TudorTudor
61.2k12 gold badges99 silver badges142 bronze badges
Break is supposed to be used in loops.
Use a return statement, which causes execution to leave the current subroutine and resume at the point in the code immediately after where the subroutine was called (return address).
answered Aug 22, 2012 at 19:42
fabiorochafabiorocha
1401 silver badge14 bronze badges
The other answers are correct, this is just a slight addition.
To return probably in this specific case you should include errno.h
like this:
#include <errno.h>
And furthermore return like this:
return EINVAL;
Then you are signaling that the program is terminating due to an error and the return value specifically states that the error is invalid arguments.
answered Aug 22, 2012 at 19:57
paldepindpaldepind
4,5603 gold badges30 silver badges35 bronze badges
‘break’ will only get you out of the innermost loop or switch. You can use ‘return’ to exit out of a function at any time.
«A break statement may appear only in an iteration statement or a switch statement, and terminates execution of the smallest enclosing such statement».
And it makes sense too — you can «escape» from a method with «return» , and you can skip code in other situations with an if/else. I don’t know what a «break» outside a case would be expected to do.
‘break’ is really only a restricted form of ‘goto’ anyway. Ideally, you want a single point of exit from any block of code. You should really only use ‘break’ in a switch statement because that is the only way to make it work. In any other context, there are better ways to accomplish the same thing. The same applies to ‘continue’.
answered Feb 26, 2014 at 5:26
Suraj K ThomasSuraj K Thomas
5,6854 gold badges51 silver badges64 bronze badges
Компилятор G ++ выдает следующую ошибку:
error: break statement not within loop or switch
Пока мой код выглядит следующим образом:
#include <iostream>
using namespace std;
int number;
int main() {
cout << "Let's check whether an integer is even or odd." << endl;
cout << "Input new for checking a new number." << endl;
cout << "Input 0 when done." << endl;
cout << "Enter a number to check whether it's even or odd." << endl << endl;
cin >> number;
if (number == 0) {
cout << "Aborted." << endl;
break;
} else if (number % 2 == 0) {
cout << "Number is even." << endl;
} else {
cout << "Number is odd." << endl;
}
return (0);
}
Как видите, break
заявление является в цикле, if
петля, чтобы быть точным. Так почему же он дает эту ошибку?
-2
Решение
Сообщение об ошибке достаточно ясно
ошибка: оператор разрыва не в пределах петля или же переключатель
Где в вашем коде есть цикл или оператор swictch, с которым вы используете оператор break?
Просто удалите оператор прерывания отсюда
if (number==0) {
cout<<"Aborted."<<endl;
break;
}
и пиши просто
if (number==0) {
cout<<"Aborted."<<endl;
}
Там же написано, что в вашей программе используется цикл. Так что программа может выглядеть
#include <iostream>
int main()
{
std::cout << "Let's check whether an integer is even or odd." << std::endl;
std::cout << "Input new for checking a new number." << std::endl;
std::cout << "Input 0 when done."<< std::endl;
while ( true )
{
std::cout << "nEnter a number to check whether it's even or odd (0-exit): ";
int number = 0;
std::cin >> number;
if ( number == 0 ) break;
if ( number % 2 == 0 )
{
std::cout<< "Number is even." << std::endl;
}
else
{
std::cout << "Number is odd." << std::endl;
}
}
return 0;
}
1
Другие решения
«break» предназначен для выхода из циклов switch / do / while / for (не для операторов if). В вашем примере нет необходимости в разрыве, поток программы просто продолжит выполнение оператора return (0), когда он достигнет того места, где сейчас находится оператор break.
0
Оператор break работает, только если он находится в цикле. Под циклом в C ++ это означает цикл, цикл while и цикл do … while. if
это проверить условие, когда отрываться от петли.
Если вы хотите, чтобы ваша программа работала (без перезапуска), поместите тестируемые операторы if в цикл (например, в цикл for).
0
Простейший цикл, который я использую:
do
{
if (number==0)
{
cout<<"Aborted."<<endl;
break;
}
else if( ... )
...}while(0);
Это будет цикл ровно один раз.
0
Switch Statement Error
I keep getting the error: break not inside of loop or switch statement. Other errors include case «2» is not within a switch or a loop. What is wrong?!?
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
int nSexy;
cout << «On a scale of one to ten, how sexy are you? 10 = sexiest 1 = oh lord no.»;
cout << endl;
cout << «Please type the number as a digit.»;
cout << endl;
cin >> nSexy;
{
{switch (nSexy)
case ‘1’:
cout << «You’re so ugly, the computer purposely lowers the graphics when you use a webcam.»;
break;
case ‘2’:
cout << «I’d rather not look at you, but if I must, wretching in disgust might be a side effect.»;
break;
case ‘3’:
cout << «Please, don’t take any pictures of yourself.»;
break;
case ‘4’:
cout << «eh.»;
break;
case ‘5’:
cout << «Not good, but alright.»;
break;
case ‘6’:
cout << «You’d be extremely hot if I were drunk.»;
break;
case ‘7’:
cout << «Baby, I could look at you all night.»;
break;
case ‘8’:
cout << «My word eleanor, who is that alluring person?»;
break;
case ‘9’:
cout << «You’re a very beautiful person.»;
break;
case ’10’:
cout << «Not even jesus is good enough for you.»;
break;
default:
cout << «say what’s that sound? I THINK ITS STUPIDITY! only stupid people don’t put a correct number. although, it might be idiocy.»;
break;
}
}
return 0;
}
READABILITY FIX
I keep getting the error: break not inside of loop or switch statement. Other errors include case «2» is not within a switch or a loop. What is wrong?!?
|
|
Last edited on
Wow, for the readability fix, i have the indentations, its just that when i copied and pasted it, the formatting disappeared. Thanks for the article though, all I was missing was one «{«.
iceadmiral wrote: |
---|
…. all I was missing was one «{«. |
You have a couple more problems than that:
You have too many braces. Delete lines 15,16,58. Add opening brace on line 17, so that the switch is now enclosed in braces.
Too many braces is a problem because it means scope, consider this:
|
|
So it is generally a bad idea to introduce gratuitous scope.
The nSexy
variable is of type int
, but you have the cases specified as char, so change it like this (remove the single quotes):
|
|
Especially here:
|
|
Wow, for the readability fix, i have the indentations, its just that when i copied and pasted it, the formatting disappeared.
Hope all is well :+)
Last edited on
Thanks, I’m a beginner so when I don’t know what’s wrong, I tend to just add things here and there and so I have a lot of extra stuff. I should have just posted on here right away…
Topic archived. No new replies allowed.
Я написал эту часть кода, и показывается серия ошибок. Вышеупомянутая ошибка является первой. Что не так в коде?
void direction(char ch)
{
switch(ch)
case 'w': if(dirn!=3){dirn=1;}
break;
case 'a': if(dirn!=2){dirn=4;}
break;
case 's': if(dirn!=1){dirn=3;}
break;
case 'd': if(dirn!=4){dirn=2;}
break;
0
Решение
Вы можете опустить открывающие и закрывающие фигурные скобки для оператора switch только в том случае, если в вашем блоке switch есть только один случай, как показано ниже:
void direction(char ch)
{
switch(ch)
case 'w': if(dirn!=3){dirn=1;}
}
Но, если у вас есть несколько случаев, с которыми нужно иметь дело, как в вашем случае, вы должны заключить их в пару открывающих и закрывающих фигурных скобок, чтобы создать блок кода для оператора switch, как показано ниже:
void direction(char ch)
{
switch(ch)
{//opening brace for starting of statement block
case 'w': if(dirn!=3){dirn=1;}
break;
case 'a': if(dirn!=2){dirn=4;}
break;
case 's': if(dirn!=1){dirn=3;}
break;
case 'd': if(dirn!=4){dirn=2;}
break;
}//closing brace for closing of statement block
Таким образом, вам придется либо удалить все случаи, но одним ИЛИ добавить пару фигурных скобок для создания блока операторов. Во всех остальных случаях ваш код не будет успешно скомпилирован.
1
Другие решения
Вы забыли о скобках переключателей:
void direction(char ch)
{
switch(ch)
{
case 'w': if(dirn!=3){dirn=1;}
break;
case 'a': if(dirn!=2){dirn=4;}
break;
case 's': if(dirn!=1){dirn=3;}
break;
case 'd': if(dirn!=4){dirn=2;}
break;
}
}
0
Для оператора switch требуется блок скобок, где все метки, включая метку по умолчанию, должны быть:
switch(ch)
{
case 'w': if(dirn!=3) dirn=1;
break;
case 'a': if(dirn!=2) dirn=4;
break;
case 's': if(dirn!=1) dirn=3;
break;
case 'd': if(dirn!=4) dirn=2;
break;
default:
break;
}
Заявление после переключения должно быть составное заявление содержать case, default и break. Разрыв здесь имеет особое значение, отличное от циклов. Если фигурная скобка была опущена, только следующая строка после switch является частью ее оператора.
0
I suspect that the description / pseudo-code is incorrect when it says:
a «break,» which was intended for the «if» clause
It would make sense if that was meant to be:
- a
break
, which was intended to terminate thedo while
loop
The problem description then makes sense.
do
{
...
switch (...)
{
case ...:
...
break;
...
case ...:
...
if (critical_condition())
break; // Intended to exit loop - actually exits switch only
...
break; // Terminates the case in the switch
}
} while (!time_to_stop());
Reading the URL referenced in the question, the pseudo-code there is:
In pseudocode, the program read as follows:
1 while (ring receive buffer not empty and side buffer not empty) DO 2 Initialize pointer to first message in side buffer or ring receive buffer 3 get copy of buffer 4 switch (message) 5 case (incoming_message): 6 if (sending switch is out of service) DO 7 if (ring write buffer is empty) DO 8 send "in service" to status map 9 else 10 break END IF 11 process incoming message, set up pointers to optional parameters 12 break END SWITCH 13 do optional parameter work
When the destination switch received the second of the two closely timed messages while it was still busy with the first (buffer not empty, line 7), the program should have dropped out of the if clause (line 7), processed the incoming message, and set up the pointers to the database (line 11). Instead, because of the break statement in the else clause (line 10), the program dropped out of the case statement entirely and began doing optional parameter work which overwrote the data (line 13). Error correction software detected the overwrite and shut the switch down while it couls [sic] reset. Because every switch contained the same software, the resets cascaded down the network, incapacitating the system.
This agrees with my hypothesis — the pseudo-code in the question is an incorrect characterization of the pseudo-code in the paper.
Another reference on the same subject (found via a Google search ‘att crash 1990 4ess’) says:
Error Description
What was reported in ACM’s Software Engineering Notes [Reference 2] is that the software defect was traced to an elementary programming error, which is described as follows:
In the offending «C» program text there was a construct of the form: [Erratic indentation as in original]
/* ``C'' Fragment to Illustrate AT&T Defect */ do { switch expression { ... case (value): if (logical) { sequence of statements break } else { another sequence of statements } statements after if...else statement } statements after case statement } while (expression) statements after do...while statement
Programming Mistake Described
The mistake is that the programmer thought that the break statement applied to the if statement in the above passage, was clearly never exercised. If it had been, then the testers would have noticed the abnormal behavior and would have been able to corr [sic]
The only caveat to this statement is the following: it is possible that tests applied to the code contain information which would reveal the error; however, if the testers do not examine the output and notice the error, then the deficiency is not with th [sic]
In the case of a misplaced break statement, it is very likely that the error would have been detected.
References
«Can We Trust Our Software?», Newsweek, 29 January 1990.
ACM SIGSOFT, Software Engineering Notes, Vol. 15, No. 2, Page 11ff, April 1990.
Apparently, the programmer really did just think that break
would end the if
statement; it was a small mental blackout that led to a large real-world blackout.
In a switch statement, if a break or return statement is not encountered, the code execution will continue from one matching case to the next.
The example given for using break statements in a switch is not convincing, as the code execution continues without any break or return statement.
Table of contents
- Using break statement in switch
- Syntax error in switch statement
- Unreachable code error when I use a break in my switch statement
- Should we break the default case in switch statement?
- What is the use of break keyword in Java?
- Does the DEFAULT keyword need a break in a switch statement?
- Why does the switch statement break so often?
- Is it bad syntax to use switch case without a break?
Using break statement in switch
Question:
Here’s an instance of implementing
break statement
s in a switch statement.
let numberSymbol: Character = "三" // Simplified Chinese for the number 3
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "١", "一", "๑":
possibleIntegerValue = 1
case "2", "٢", "二", "๒":
possibleIntegerValue = 2
case "3", "٣", "三", "๓":
possibleIntegerValue = 3
case "4", "٤", "四", "๔":
possibleIntegerValue = 4
default:
break
}
if let integerValue = possibleIntegerValue {
println("The integer value of \(numberSymbol) is \(integerValue).")
} else {
println("An integer value could not be found for \(numberSymbol).")
}
The utilization of breaks in switch statement (
possibleIntegerValue
) is not necessarily superior to other options. An alternative such as (
possibleIntegerValue = nil
) can be just as effective. This is due to the fact that (
optional Int
).
let numberSymbol: Character = "三" // Simplified Chinese for the number 3
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "١", "一", "๑":
possibleIntegerValue = 1
case "2", "٢", "二", "๒":
possibleIntegerValue = 2
case "3", "٣", "三", "๓":
possibleIntegerValue = 3
case "4", "٤", "四", "๔":
possibleIntegerValue = 4
default:
possibleIntegerValue = nil
}
if let integerValue = possibleIntegerValue {
println("The integer value of \(numberSymbol) is \(integerValue).")
} else {
println("An integer value could not be found for \(numberSymbol).")
}
In this scenario, there is no need for
break
. Could someone provide me with an appropriate illustration of utilizing breaks in a switch statement, where certain cases are intentionally disregarded?
The book says:
To match and ignore cases in a
switch statement
, you can use this technique. The
Swift’s switch
statement is exhaustive and doesn’t permit empty cases. However, there may be cases where you deliberately want to match and disregard a case to make your intentions clear. In such cases, you can write the break statement as the entire body of the case you want to ignore, and this will cause the switch statement’s execution to end immediately when that specific case is matched.
Solution:
When you need to include a case in your logic for clarity purposes, but it does not require any actual functionality, you can use the
break
statement inside a
switch
. For instance, let’s say you want to use a
switch
statement to determine whether to
Determine if a given year is a leap year
or not, even though it may seem like a contrived example.
func isLeapYear(year: Int) -> Bool {
switch (year) {
case let x where (x % 100) == 0 && (x % 400) != 0:
break
case let x where (x % 4) == 0:
return true
default:
break
}
return false
}
isLeapYear(2014) // false
isLeapYear(2000) // true
isLeapYear(1900) // false
In
isLeapYear
, utilizing the first instance of
switch
helps in identifying the exceptional non-leap years, which are the years that are both divisible by 100 and not divisible by 400. In such cases, the
break
statement corresponds to taking no action.
Switch Statement in C/C++, In C++, the switch statement is used for executing one condition from multiple conditions. It is similar to an if-else-if ladder. Switch statement consists of conditional based cases and a default case. In a switch statement, the “case value” can be of “char” and “int” type. Following are some of the rules while …
Syntax error in switch statement
Question:
Here’s the issue at hand: I’m working with a switch-statement that requires me to verify if a particular string matches a specific symbol. However, the current code implementation seems to be causing some trouble.
[...]
switch($str) {
[...]
case (: $output .= $example_array[rand(0,3)] . '|'; break;
case ): $output .= $example_array[rand(4,8)] . '|'; break;
[...]
}
[...]
I get the following error:
An error occurred while parsing the code, specifically an unexpected ‘case’ (T_CASE) in […]
Is there a way to avoid changing my statement to either
if
or
else
, or can I find a workaround?
Solution 1:
It could be helpful to review the structure of the code in
switch
.
To match the desired character, it is necessary to enclose it in quotation marks.
case "(":
$output .= $example_array[rand(0,3)] . '|';
break;
Solution 2:
When assessing a string that contains parentheses, it is recommended to use quotation marks.
case ')':
case '(':
Error: break statement not within loop or switch, Error: break statement not within loop or switch. Ask Question Asked 5 years, 6 months ago. Modified 5 years, 6 months ago. Viewed 2k times The statement after switch must be a compound statement to contain case, default and break. Break got a special meaning here, different from loops. If …
Unreachable code error when I use a break in my switch statement
Question:
I am perplexed as to where I am going wrong in my code. My objective is to accomplish the following task:
switch (action.type) {
case TYPES.ADD_TO_FAVORITES:
if (state.faves.length <= 10) {
return assign({}, state, {
faves: state.faves.concat(action.payload),
full: false
});
} else {
return assign({}, state, {
faves: state.faves,
full: true
});
}
default:
return state;
}
According to my code checker, I need to include a break prior to the case labelled
default
. However, upon implementing this suggestion, my checker then gives me an error message denoted by
unreachable code
.
Solution 1:
The eslint linter rule ‘no-fallthrough’ is designed to prevent inadvertent fallthrough from one case to another.
If there is no break or return encountered, the code execution will persist from the matching case to the following cases.
At times, there may be a requirement for this, but it is essential to avoid unintentional fallthrough, which is precisely what this rule aims to prevent.
Disabling the rule or setting it as a warning can be done. However, it is suggested to assign a variable for the return value within the function and to simply return it at the end, rather than disabling the rule altogether.
function() {
var returnvalue;
Switch(variableA) {
Case 1:
returnvalue = somevalue;
break;
case 2:
returnvalue = some other value;
break;
default:
returnvalue= default value;
}
return returnvalue;
}
Upon exiting your if-else block, you will be returning from the portion that cannot be reached.
The break statement will not have an opportunity to be executed.
Solution 2:
switch (action.type) {
case TYPES.ADD_TO_FAVORITES:
if (state.faves.length <= 10) {
return ...;
} else {
return ...;
}
break; // YOU HAVE ADDED BREAK HERE
default:
return state;
}
In
case TYPES.ADD_TO_FAVORITES
, either
if
or
else
will be executed. If an object is returned in either the if or
else
, then any code added after
break
and before
default
will never be executed.
The reason for the inclusion of
unreachable code
is explicitly stated.
Solution 3:
It is not sensible and prohibited to have a return statement within a switch block. The only valid place to use the return statement is inside a function. To obtain a value from the switch statement, you may assign it to a variable.
var result;
switch (action.type) {
case TYPES.ADD_TO_FAVORITES:
if (state.faves.length <= 10) {
result = assign({}, state, {
faves: state.faves.concat(action.payload),
full: false
});
} else {
result = assign({}, state, {
faves: state.faves,
full: true
});
}
break;
default:
result = state;
break;
}
Switch statement fall-throughshould it be allowed?, It can be very useful a few times, but in general, no fall-through is the desired behavior. Fall-through should be allowed, but not implicit. switch (version) { case 1: // Update some stuff case 2: // Update more stuff case 3: // Update even more stuff case 4: // And so on } It is powerful and dangerous.
Should we break the default case in switch statement?
Question:
Presuming the code example (taken from the source):
#include
void playgame()
{
printf( "Play game called" );
}
void loadgame()
{
printf( "Load game called" );
}
void playmultiplayer()
{
printf( "Play multiplayer game called" );
}
int main()
{
int input;
printf( "1. Play game\n" );
printf( "2. Load game\n" );
printf( "3. Play multiplayer\n" );
printf( "4. Exit\n" );
printf( "Selection: " );
scanf( "%d", &input );
switch ( input ) {
case 1: /* Note the colon, not a semicolon */
playgame();
break;
case 2:
loadgame();
break;
case 3:
playmultiplayer();
break;
case 4:
printf( "Thanks for playing!\n" );
break;
default:
printf( "Bad input, quitting!\n" );
break;
}
getchar();
return 0;
}
Is it necessary to utilize a
break;
in the final
default
scenario? Although the program functions in the same way when it is removed, I have observed that other instances implement a
break;
in the
default
situation.
Why? Is there a reason?
Solution 1:
Is it necessary to include a break statement in the final default case?
Here’s an excerpt from the second edition of «The C programming language,» also known as K&R 2.
Section 3.4 focuses on the topic of switches.
It’s always good practice to include a break statement after the final case, even if it’s not logically required. This defensive programming technique can prove to be helpful in the future, in case a new case is added at the end.
Solution 2:
Consider the rationale behind implementing
break
within a switch statement. Take into account the scenario without
breaking switch statement
.
switch ( input ) {
case 1: /* Note the colon, not a semicolon */
playgame();
case 2:
loadgame();
case 3:
playmultiplayer();
case 4:
printf( "Thanks for playing!\n" );
default:
printf( "Bad input, quitting!\n" );
}
If
input == 1
is supposed to happen, the program will naturally invoke
playgame()
. However, if there’s a lack of
break
, the program cannot complete the
switch
and will instead execute
loadgame()
, followed by
playmultiplayer()
, and two
printf
s consecutively.
In order to prevent it, we employ
break
.
case 1:
playgame();
break; /* here */
case 2:
...
The expected outcome is for the program to finish executing the
switch
statement before moving on to the codes of
case 2
, which is due to
break
.
Your switch is this:
switch ( input ) {
case 1: /* Note the colon, not a semicolon */
playgame();
break;
case 2:
loadgame();
break;
case 3:
playmultiplayer();
break;
case 4:
printf( "Thanks for playing!\n" );
break;
default:
printf( "Bad input, quitting!\n" );
break;
}
If there is no occurrence of
case
following
default
, then it makes no difference whether or not you include
break
on
default
. Nevertheless, it is simple to assume a new scenario to write.
default:
printf( "Thanks for playing!\n" );
/* what happens if there's no `break`...? */
case 5:
the_new_feature();
break;
}
It is typical to make errors in C/C++, and if a new feature is added and then forgotten after five years, it can result in a highly flawed bug. In fact, some contemporary languages like C# prohibit switch-case without either
break
or
return
.
The syntax appears to be error-free; however, it is strongly advised to avoid the practice mentioned and instead opt for
break
.
Solution 3:
The outcome is contingent on the manner in which the default case is composed.
In this particular instance, it is essential to have a break.
switch ( input ) {
default:
printf( "Bad input, quitting!\n" );
break;
case 1: /* Note the colon, not a semicolon */
playgame();
break;
case 2:
loadgame();
break;
}
Solution 4:
Whether you exclude or retain the
break
statement, it is merely a matter of preference and will not alter the outcome.
It is beneficial to include the break statement in code for various purposes.
Have a glance at the programmers’ forum.
Why do we need break after case statements?, The break after switch case s is used to avoid the fallthrough in the switch statements. Though interestingly this now can be achieved through the newly formed switch labels as implemented via JEP-325. With these changes, the break with every switch case can be avoided as demonstrated further :-.