undefinedfix
Sign in

Error report of C language break statement

wzvst edited in Tue, 23 Feb 2021

I don't know what's wrong. I've been reading it for a long time, but I don't know how to change it

#include<stdio.h>
#include<time.h>
#include<stdlib.h>
main()
{
    int rollDice();
    void delay();
    int i,result = 0 ,result1 = 0;
    printf("Game Start!!!!\n");
    result = rollDice();
    printf("%d\n",result);
    delay();
    if ((result == 7 )||(result == 11))
        {printf("Y\n");break;}
    else if ((result == 2) || (result == 3)|| (result == 12))
        {printf("N\n");}
    else
        printf("C\n");
        for (i = 0;i<7;i++)
            {result1 = rollDice();
            printf("%d\n",result1);
            if (result1==result)
                {printf("Y\n");break;}
            else if ((result1!=result)&&(i==6))
                printf("N\n");
        }
    return 0;
}
int rollDice()
{
     void delay();
     int a,b,c;
         srand((unsigned)time(NULL));
         a= rand()%6 + 1;
         delay();
         b= rand()%6 + 1;
         c = a + b;
     return c;
}
void delay()
{
    long t;
    for (t=0;t<50000000;t++)
    {

    }
}
4 Replies
bszsk
commented on Tue, 23 Feb 2021

Break must be used improperly in the first cycle. The second break will do. It is suggested that you unify the code format and add curly braces when there are curly braces. Change the code to this:

int rollDice();
void delay();
int i,result = 0 ,result1 = 0;
printf("Game Start!!!!\n");
result = rollDice();
printf("%d\n",result);
delay();
if ((result == 7 )||(result == 11))
    {printf("Y\n");}
else if ((result == 2) || (result == 3)|| (result == 12))
    {printf("N\n");}
else
    {printf("C\n");}
    
    
    
    
    for (i = 0;i<7;i++)
        {result1 = rollDice();
        printf("%d\n",result1);
        if (result1==result)
            {printf("Y\n");break;}
        else if ((result1!=result)&&(i==6))
            printf("N\n");
    }
    
return 0;
Ryan
commented on Tue, 23 Feb 2021

The break statement has two uses: 1. It is used in the switch statement to exit the switch statement halfway. 2. Used in loop statements to exit the current loop directly from the loop body.

The first break statement of the subject does not belong to either usage.

Amer
commented on Tue, 23 Feb 2021

There are three problems with your code:

1. The main() function has no return value type

2. Rolldice() and delay() are called without prior declaration

3. Wrong use of break

Any of the above three points is enough to cause the program to report an error directly.

In addition, I advise you to master the basic language skills first, and then debug more.

angelinebraun
commented on Wed, 24 Feb 2021

Break is used to jump out in the while statement, switch statement, do {} while, for {} Henan opera

Not used to jump out of if / else

lock This question has been locked and the reply function has been disabled.