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.1k12 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
|
pusherlove 0 / 0 / 0 Регистрация: 01.02.2017 Сообщений: 18 |
||||
|
1 |
||||
|
10.01.2020, 15:10. Показов 8615. Ответов 3 Метки нет (Все метки)
__________________
0 |
|
Диссидент
27184 / 16942 / 3744 Регистрация: 24.12.2010 Сообщений: 38,125 |
|
|
10.01.2020, 15:20 |
2 |
|
while (i!=1); Точку с запятой убери.
0 |
|
3972 / 3243 / 907 Регистрация: 25.03.2012 Сообщений: 12,063 Записей в блоге: 1 |
|
|
10.01.2020, 15:22 |
3 |
|
ну и зачем тут break? какой в нём смысл? Что такое while(i!=1) если у тебя i нигде не задаётся?
0 |
|
Байт |
|
10.01.2020, 15:25
|
|
Не по теме: Kuzia domovenok, на общую бредовость кода внимания не обратил.:D
0 |
- Forum
- Beginners
- Break statement not within loop or switc
Break statement not within loop or switch
I know it must be something really stupid, but I can’t figure it out.
|
|
What are you trying to do…?
use cin.getchar() instead of cin.get()…
I’m still learning. This is part of the code of an exercise of a book. I don’t know cin.getchar() yet. Do you spot any error with cin.get()?
The problem is that the first loop ends on line 1 because you put a semicolon at the end of the line.
@HiteshVaghani1
What is the difference between cin.getchar() and cin.get()?
Oh my god. I knew it had to be something really stupid. And indeed it is.
Thank you very much for all your help.
@Peter87
Actually there is not difference between cin.get() and cin.getchar() in working purpose.
For cin.get() we have to include <iostream> and for getchar() we have to include <cstdio>.
here break statement is never reached because of the continue statement used just before the break statement
Last edited on
Topic archived. No new replies allowed.
