Simple if statement in C

if statement is used in conjunction with expressions. It takes the following form.

// syntax for simple if
if(test_expression){
  // statement-block/statements to be executed 
}
// other statements

statement block is either single statement or group of statements. If test expression is true or non-zero then the statement block is executed, otherwise the statement block is skipped and the flow passes to the other statements.

The curly brace is to make a block scope, however, the brace is optional. If we remove braces then the only one statement will be in the success scope of the if. Meaning that if no such braces exists after if then it only treats first statement as statement-block. The expression will look like.

if(test_expression)
  // statement to be executed when test_expression is true
// other statements

But, it is highly recommended to use braces with if statement.

The simple if statement can be illustrated in the following flowchart.

Simple if statement flowchart

Let’s look at practical scenario, where we can use simple if construct.

You have an integer number. You are required to check, whether the number is divisible by 5. You just have to check if the number is divisible by 5. You can use modulo operator along with if construct. The C program will look like the following.

#include <stdio.h>
int main(){
  int number;
  printf("Enter an integer number:");
  scanf("%d", &number);

  // simple if condition
  if(number % 5 == 0){
    printf("It is divisible by 5.\n");
  }
  return 0;
}

Test expression number % 5 == 0, first evaluates number % 5 and then result is compared with 0 using equality operator. If the expression number % 5 results 0, then the number is divisible by 5. i.e. expression will be 0 == 0, which finally evaluates to be true causing the if block to execute. Let’s say if the number is not divisible by 5. i.e. the result of number % 5 will result some number. Final result of some_number == 0 will result false causing the if block to skip.

This simple if construct does not care about false condition. In above example it does not care about if the number is not divisible by 5. It simply skips the if block.