Ошибка 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],"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,6403 gold badges30 silver badges36 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

178k25 gold badges365 silver badges392 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.4k12 gold badges101 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,6403 gold badges30 silver badges36 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,7354 gold badges52 silver badges64 bronze badges

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;
}

Компилятор 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

pusherlove

0 / 0 / 0

Регистрация: 01.02.2017

Сообщений: 18

1

10.01.2020, 15:10. Показов 9449. Ответов 3

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

C++
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
#include <iostream>
using namespace std;
 
 
int main()
{
    int a, b, nok, nod, x, y, i;
    cout << "m = ";
    cin >> a;
    cout << "n = ";
    cin >> b;
    x = a;
    y = b;
            while (i!=1);
    {
        if (a > b)
            a = a - b;
        else
            b = b - a;
        if (a == b)
        {
            nod = a;
            nok = (x*y) / nod;
            
        }
        break;
    }
    
    cout <<"NOK = "<<nok<<endl;
    return 0;
}



0



Диссидент

Эксперт C

27532 / 17220 / 3788

Регистрация: 24.12.2010

Сообщений: 38,772

10.01.2020, 15:20

2

Цитата
Сообщение от pusherlove
Посмотреть сообщение

while (i!=1);

Точку с запятой убери.



0



4030 / 3286 / 921

Регистрация: 25.03.2012

Сообщений: 12,289

Записей в блоге: 1

10.01.2020, 15:22

3

ну и зачем тут break? какой в нём смысл? Что такое while(i!=1) если у тебя i нигде не задаётся?
может ты хотел сделать цикл whie(a!=b) ?



0



Байт

10.01.2020, 15:25


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

Не по теме:

Kuzia domovenok, на общую бредовость кода внимания не обратил.:D



0




0

1

Вопрос касается использования ({})-расширения.

for(int i=0;i<3;({break;}));
 -> error: break statement not within loop or switch

for(int i=0;i<3;i++)
 for(int j=0;j<3;({break;}))
  printf("%d - %dn",i,j);
 -> 0 - 0
    1 - 0
    2 - 0

То есть в первом случае компилятор не дает использовать ({break;}) внутри «шапки» (не знаю, как правильно назвать) цикла, а во втором преспокойно обрывает цикл, в шапке которого он указан. Получается, на этапе обработки семантических ошибок он рассматривает брэйк внутри внешнего цикла, а на этапе трансляции перемещает его во внутренний.

Гцц-4.4.4, сейчас собираю 4.5.2. Раньше, емнип, такого безобразия я не наблюдал, и компилятор на обоих этапах вел себя будто брэйк относится к тому циклу, в шапке которого указан. Мне кажется это логичным: третья часть (step) шапки for-а должна выполняться после каждой итерации, таким образом вырубать цикл после первого прохода.

ПС. Изврашаться с языком приходится, чтобы соорудить макрос.

  • Ошибка brake на хендай акцент
  • Ошибка brake wear visit workshop на мерседес w211
  • Ошибка brake system service required
  • Ошибка brake pads audi a6 c6
  • Ошибка brake light ситроен с4