C if statement

The target

In this article, you’ll learn how to use C if statements to execute blocks of code based on conditions.

This section describes the C if statement

The if statement allows you to run blocks of code based on conditions. The syntax for the if statement is as follows:

If (expression) statement;Copy the code

The if statement evaluates an expression. If the expression evaluates to true(or a non-zero value), the If statement executes that statement.

However, if the expression evaluates to false(or 0), the if statement does not execute the statement and passes control to subsequent statements.

Note that C treats 0 as false and non-zero values as true.

The following flowchart illustrates how the if statement works:

If you are older than 16, the following example uses the if statement to display a message on the screen:

#include <stdio.h> #include <stdbool.h> int main() { int age = 20; If (age > 18) printf(" You can drive." ); return 0; }Copy the code

Since age is 20, you will see the following message in the output:

You can drive.Copy the code

To form complex conditions, logical operators can be used, including logical and operators, logical or operators, and logical non-operators.

The following example uses an if statement with compound conditions:

#include <stdio.h> #include <stdbool.h> int main() { int age = 20; bool have_driving_license = true; If (age > 18 &&have_driving_license) printf(" You can drive." ); return 0; }Copy the code

Since age is 20 and have_driveing_license is true, you will see the following information in the output:

You can drive.Copy the code

If you change age to a value less than 18, or change have_driving_license to false, you will see nothing in the output.

Execute multiple statements using if statements

To execute multiple statements based on a condition, use the following if statement:

If (expression) {statement 1; Statements 2; / /... }Copy the code

In this syntax, statements are wrapped in curly braces ({}).

The following example uses an if statement to execute multiple statements:

#include <stdio.h> int main() { int age = 20; If (age > 18) {printf(" You can drive. \n"); Printf (" You can take a driver's license. \n"); } return 0; }Copy the code

Since age is greater than 18, you should see the following in the output:

You can drive. You can take a driving test.Copy the code

Note that there is no semicolon at the end of the if statement like this:

If (expression); {statement 1; }Copy the code

If you place a semicolon (;) like above The statement in the block following the If statement is always executed.

The reason is that C treats this code as an if statement with no body:

If (expression);Copy the code

And a code block:

{statement 1; }Copy the code

This code block does not depend on the if statement above.

conclusion

  • Use C if statements to execute one or more statements based on conditions.