- C language
- Basic grammar
- here
if statement --conditional branch
I will explain about conditional branching in C language.
if statement
Use a
if statement to do a conditional branch.
if (condition) {
// Processing to be executed when the conditions are met
}
As for the truth value in C language, 0 is false and other values are true. NULL is defined as 0 in C, so it is false.
This is a sample if statement.
The comparison operator is 1 if it is satisfied and 0 if it is not.
#include <stdio.h>
#include <stdint.h>
int main (void) {
int32_t flag = 1;
if (flag == 1) {
printf("1 OK\n");
}
}
Output result.
1 OK
else if statement
If you want to write multiple conditions, use else if statement . You can write multiple else if statements.
if (condition 1) {
// Processing to be executed when condition 1 is met
}
else if (condition 2) {
// Processing to be executed when condition 2 is met
}
else if (condition 3) {
// Processing to be executed when condition 3 is met
}
This is a sample of else if statement.
#include <stdio.h>
#include <stdint.h>
int main (void) {
int32_t flag = 2;
if (flag == 1) {
printf("1 OK\n");
}
else if (flag == 2) {
printf("2 OK\n");
}
}
Output result.
2 OK
else statement
If you want to execute the process when the condition is not met, use the else statement.
if (condition) {
// Processing to be executed when the conditions are met
}
else {
// Processing to be executed when the condition is not met
}
if (condition 1) {
// Processing to be executed when condition 1 is met
}
else if (condition 2) {
// Processing to be executed when condition 2 is met
}
else if (condition 3) {
// Processing to be executed when condition 3 is met
}
else {
// Processing when all the above conditions are not met
}
This is a sample of the else statement.
#include <stdio.h>
#include <stdint.h>
int main (void) {
int32_t flag = 3;
if (flag == 1) {
printf("1 OK\n");
}
else if (flag == 2) {
printf("2 OK\n");
}
else {
printf("Not OK\n");
}
}
Output result.
Not OK
C Language Zemi