Search code examples
cloopsdo-whilebreakgoto

break statement not working in else statement


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

Solution

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