How to terminate the execution of an “if” statement in the C language?

In C language, the execution of the if statement depends on the value of the conditional expression. If the value of the conditional expression is true (non-zero), the code in the if statement block will be executed; if the value of the conditional expression is false (0), the code in the if statement block will be skipped.

The program will continue executing the code after the if statement, regardless of whether the if statement is executed or not. This means that after the code in the if statement block is finished executing, the program will automatically proceed with the next statement.

To exit an if statement block when a certain condition is met, you can use either the break statement or the return statement. The break statement is used to exit the current loop or switch statement, while the return statement is used to end the function’s execution and return a value.

Below is an example of ending an if statement execution using the break and return statements.

#include <stdio.h>

int main() {
    int num = 5;

    if (num > 0) {
        printf("num is positive\n");
        break; // 使用break语句跳出if语句块
    }

    printf("This line will always be executed\n");

    return 0;
}
#include <stdio.h>

int main() {
    int num = 5;

    if (num > 0) {
        printf("num is positive\n");
        return 0; // 使用return语句结束函数的执行
    }

    printf("This line will not be executed\n");

    return 0;
}

In the above example, if the value of num is greater than 0, the code inside the if statement block will be executed, then the break or return statement is used to exit the if statement block. If the value of num is less than or equal to 0, the code inside the if statement block will be skipped, and the program will directly execute the next statement.

bannerAds