Ошибка break statement not within loop or switch break

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],"

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's user avatar

paldepind

4,5603 gold badges30 silver badges35 bronze badges

asked Aug 22, 2012 at 19:37

Teja's user avatar

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

cnicutar's user avatar

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 Miller's user avatar

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

Tudor's user avatar

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

fabiorocha's user avatar

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

paldepind's user avatar

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 Thomas's user avatar

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?!?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#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;
}

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{ // outer scope
{
int a =1;
std::cout << "First a is " << a << "n";
} // end of first a's scope

{  // braces mean a different scope
         int a = 2; // different to the other a
         std::cout << "Second a is " << a << "n";
} // end of second a's scope
int a =3; // this a is in the outer scope
{  // braces mean a different scope
         int a = 4; // error a = 3 still in scope
         std::cout << "Third  a is " << a << "n";  // a is 3
}

} //end of outer scope 

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):

19
20
21
22
23
24
        case 1: // int not char
                cout << "You're so ugly, the computer purposely lowers the"
                    << "graphics when you use a webcam.";
               break;

        case 2:  // int not char 

Especially here:

49
50
51
        case '10':  // char can only hold 1 char
                cout << "Not even jesus is good enough for you.";
                break;

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.

Понравилась статья? Поделить с друзьями:
  • Ошибка bravo 04 the division 2
  • Ошибка brake хендай акцент
  • Ошибка brake бмв х5 е53
  • Ошибка brake pads audi a6 c6
  • Ошибка brake light ауди