0

I am getting this error in c. I was using the "break" statement in the else statement and get this error message "error: break statement, not within loop or switch."

#include <stdio.h>
void main()
{
    int click;
    scanf("%d",&click);
    first_page:
        if(click == 1)
        {
            printf("OK");
        }
        else
        {
            printf("\nInvalid");
            goto first_page;
                break;
        }
}
Auvee
  • 95
  • 2
  • 15
  • The error actually tells you all you need to know ... that ain't how break works. – X39 Aug 15 '19 at 16:55
  • 1
    Why did you try to put the `break` statement not within loop or switch in the first place?nwyat did you expect it to do? – ForceBru Aug 15 '19 at 16:56
  • 4
    A `break` doesn't act on an `if`/`else`. Also, you'll never even reach that `break`, the `goto` will take you away first. – Thomas Jager Aug 15 '19 at 16:56
  • Also, [read this](https://stackoverflow.com/questions/3517726/what-is-wrong-with-using-goto) on why gotos are bad. – selbie Aug 15 '19 at 17:01
  • You're using `goto` to create an infinite loop. The standard way to create an infinite loop in C is with `while(1)` or `for(;;)`. Then you can end the loop with `break`. Of course, you need to move the `scanf` into the loop, or the loop will never break. – user3386109 Aug 15 '19 at 17:01
  • 1
    Isn't `first_page:` in the wrong place anyway? The code is quite bizarre. – Weather Vane Aug 15 '19 at 17:02

1 Answers1

3

The break statement may appear only in an iteration statement or a switch statement.

From the C Standard (6.8.6.3 The break statement)

1 A break statement shall appear only in or as a switch body or loop body.

In your program it is redundant. The program has an infinite loop.

It seems what you mean is the following.

#include <stdio.h>

int main( void )
{
    int click;

    do
    {
        scanf("%d",&click);

        if(click == 1)
        {
            printf("OK");
        }
        else
        {
            printf("\nInvalid");
        }
    } while ( click != 1 );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335