Prev Page Next Page

If Statement

Formal Definition

The if statement is used to choose which statement should be executed depending on the conditional expression.

Simplified Syntax

if (conditional expression)

  statement1;

else

  statement2;

if (conditional expression)

  statement1;

else if (conditional expression)

  statement2;

else

  statement3;

Description

The 'if' statement can be used in two ways: as a single 'if-else' statement (Example 1) or as a multiple 'if-else-if' statement (nested if statement - Example 2).

In the first case when the conditional expression is evaluated to true (or non-zero), then statement1 is executed and if condition is false (or zero), then statement2 is executed.

In the second case, if the first conditional expression is evaluated to be true, then statement1 is executed. Otherwise, the second conditional expression is evaluated and depending on its values, statement2 or statement3 is executed.

Every statement can be a group of statements (enclosed in a begin-end block - Example 3) or a null statement (; - Example 4). The conditional expression can be any valid expression.

Examples

Example 1

if (a == 5)
  b = 15;
else
  b = 25;

If 'a' is 5 then 'b' will be 15. Otherwise 'b' will be 25.

Example 2

if (a)
  b = 4;
else if (d)
  b = 5;
else
  b = 1;

If 'a' has non-zero value then 'b' will be 4.

If 'a' is 0 and 'd' has non-zero value then 'b' will be 5.

If 'a' is 0 and 'd' is 0 then 'b' will be 1.

Example 3

if (a)
  begin
  counter = counter + 1;
  data_out = counter;
  end
else
  data_out = 8'bz;

If 'a' has non-zero value then the counter variable will be incremented and a new counter value will be assigned to data_out variable. Otherwise, data_out bits will be assigned a high-impedance value.

Example 4

if ( counter > 10)
;
else
counter = counter + 1;

If counter value is bigger than 10, then it will stop (execute a null statement - ;). If the counter value is less than 10 then it will be incremented by 1.

Important Notes

 
Prev Page Next Page
Powered by IXwebhosting