Search code examples
cbreak

break a loop then not run next code if loop breaks


#include <stdio.h>

int main() {
    while (height > 0) {
        if (throttle >= 0 && throttle <= 100) {
            printf("%d    %.1f  %.1f   %.1f  ", time, height, velocity, fuel);
            scanf("%d", &throttle);
            height = heightTemp + velocityTemp - (throttle * K-G) / 2;
            velocity = velocityTemp + (throttle * K-G);
            fuel = fuelTemp - throttle;
            time = time + 1;
            heightTemp = height;
            velocityTemp = velocity;
            fuelTemp = fuel;   
        }
        else {
            printf("Please choose a number between 0 and 100! \n");
            break;
        }
    }
   
    if (velocity >= -2.0) {
        printf("You landed successfully: ");
    } 
    else {
        printf("Failed! You crashed");
    }

    return 0;
}

I want to only run the if velocity part if the loop does not break, if I keep the code this way it'll run that code no matter what since the break obviously only quits the loop. My full code is not written.


Solution

  • There are basically two solutions to this:

    1. use a idBreak variable that you set to 1 upon breaking, like in the mikyll98's answer
    2. use a goto pastTheIfElse; instead of break;.

    If the pastTheIfElse label marks a return (like it does in your code), then you can directly return instead of the goto.

    #include <stdio.h>
    
    int main() {
        while (height > 0) {
            if (throttle >= 0 && throttle <= 100) {
                printf("%d    %.1f  %.1f   %.1f  ", time, height, velocity, fuel);
                scanf("%d", &throttle);
                height = heightTemp + velocityTemp - (throttle * K-G) / 2;
                velocity = velocityTemp + (throttle * K-G);
                fuel = fuelTemp - throttle;
                time = time + 1;
                heightTemp = height;
                velocityTemp = velocity;
                fuelTemp = fuel;   
            }
            else {
                printf("Please choose a number between 0 and 100! \n");
                goto pastTheIfElse; //instead of break;
                //OR in this case: `return 0;`
            }
        }
    
        if (velocity >= -2.0) {
            printf("You landed successfully: ");
        } else {
            printf("Failed! You crashed");
        }
        pastTheIfElse:
    
        return 0;
    }
    

    The goto solution is what an optimizing compiler should optimize the didBreak version into, so some prefer it, while others are really really strongly against it because "goto considered harmful".