C - Statement if Statement

Introduction

To make a decision based on relational operator, use the if statement.

The general form or syntax of the if statement is:

if(expression){
  Statement1;
}
Next_statement;

The second line could be written directly following the first, like this:
if(expression) Statement1;

The expression in parentheses can be any expression that results in a value of true or false.

If the expression is true, Statement1 is executed, after which the program continues with Next_statement.

If the expression is false, Statement1 is skipped and execution continues immediately with Next_statement.

There are three if statements here.

int myScore = 169;                   
int yourScore = 175;                 
if(yourScore > myScore)
  printf("You are better than me.\n");
if(yourScore < myScore)
  printf("I am better than you.\n");

if(yourScore == myScore)
  printf("We are exactly the same.\n");

The control expression for an if statement is expected to produce a Boolean result.

The compiler will convert the result of an if expression that produces a numerical result to type bool.

You'll sometimes see this used in programs to test for a nonzero result of a calculation.


if(count)
  printf("The value of count is not zero.\n");

This will only produce output if count is not 0, because a 0 value for count will result in false for the value of the if expression.

Any nonzero value for count will result in true for the expression.

Related Topics

Quiz

Exercise