简体   繁体   中英

About break statement in c programming and termination of a loop

I have a doubt regarding the break statement in this program.
Technically the break statement terminates the loop it is presented in, but in this program the break is inside the if statement.
So, here the break should only terminate the if statement, right? But it is also terminating the do-while statement.
Sorry if I asked something wrong. I am new to programming

#include <stdio.h>

int main()
{
    int count;
    char response;

    for (count = 1; count <= 100; count++)
    {
        printf("count = %d\n", count);
    
        printf("enter y to continue or any other key to quit");
    
        scanf(" %c", &response);
    
        if (response != 'y')
            break;
    }

    printf("thank you!\n");
    return 0;
}

According to the C Standard (6.8.6.3 The break statement)

2 A break statement terminates execution of the smallest enclosing switch or iteration statement.

This break statement in this if statement

if (response !='y')
    break;

terminates execution of the enclosing for statement.

You may imagine its action the following way

for (count=1;count<=100;count++){
    //...    
    if (response !='y')
    goto L1;
}
L1:
printf("thankyou!");

You may not use the break statement in an if statement if the if statement is not enclosed in an iteration or switch statement.

The break statement is a jump statement that passes the control outside the smallest enclosing switch or iteration statement.

You can use "break" statement in two state.

  1. In the looping
  2. In the switch-case If you use in the looping. When the break statement works, loop will be end. If you use in the switch-case.When the break statement works in the one of the cases, other cases does not work. Implicitly, the loop is over, if block will not run again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM