Break statement not within loop or switch

Компилятор G ++ выдает следующую ошибку:

error: break statement not within loop or switch

Пока мой код выглядит следующим образом:

Как видите, break заявление является в цикле, if петля, чтобы быть точным. Так почему же он дает эту ошибку?

Решение

Сообщение об ошибке достаточно ясно

ошибка: оператор разрыва не в пределах петля или же переключатель

Где в вашем коде есть цикл или оператор swictch, с которым вы используете оператор break?

Просто удалите оператор прерывания отсюда

Там же написано, что в вашей программе используется цикл. Так что программа может выглядеть

Другие решения

«break» предназначен для выхода из циклов switch / do / while / for (не для операторов if). В вашем примере нет необходимости в разрыве, поток программы просто продолжит выполнение оператора return (0), когда он достигнет того места, где сейчас находится оператор break.

Оператор break работает, только если он находится в цикле. Под циклом в C ++ это означает цикл, цикл while и цикл do … while. if это проверить условие, когда отрываться от петли.

Если вы хотите, чтобы ваша программа работала (без перезапуска), поместите тестируемые операторы if в цикл (например, в цикл for).

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().

6 Answers 6

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.

First of all make sure you are including the needed header files:

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:

Or if you want to continue the program after displaying that message you could just do this:

You only use break in loops like so:

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 .

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

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:

And furthermore return like this:

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.

‘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’.

If user input is 0, the loop ends,what is wrong?

using namespace std;

int balance=0, withdrawal=0, deposit=0;

for (int i=0; i > a;

5 Answers

Its by design that the loop should end when a = 0. That’s what the break there does. If you want to continue running the loop no matter what, remove the break statement. Maybe you pasted it wrong here, but the second < from the top is in a weird place.

  • Log in to reply to the answers Post

Your break statement is inside an else block, but not a loop.

It looks like you intended for it and the surrounding if else blocks to be inside the for loop. However, without adding braces to the for loop, it will only run for the very next line after the for statement itself, which in this case is an output call. Here, I’ll mark the code to make it easier to see:

for (int i=0; i > a; /*This line, and all the lines following it, are NOT inside the loop body. They will only be run once.*/

I think what you intended to do was this:

for (int i=0; i > a; /*Now this line is inside the loop body too.*/

> /*This is the last line inside the loop body.*/

> /*This is the closing brace for the loop.*/


[an error occurred while processing the directive]
Карта сайта