Tuesday, November 26, 2013

Conditional Statements in Verilog

conditional-statements-verilog
Conditional statements are used for making decisions based upon certain conditions. These conditions are used to decide whether or not a statement should be executed. Keywords if and else are used for conditional statements. There are three types of conditional statements in Verilog: No else statement, One else statement, and Nested if-else-if as shown below.


Type 1 conditional statement: No else statement.
// Statement executes or does not execute.
------------------------------------------------------  
if (<expression>)  true_statement;                                         

               
Type 2 conditional statement: One else statement.
// Either true_statement or false_statement is evaluated.
------------------------------------------------------ 2'b01) O = b;  
if (<expression>) true_statement;    else false_statement;  


Type 3 conditional statement: Nested if-else-if.
// Choice of multiple statements. Only one is executed.
------------------------------------------------------
if (<expression_1>)  true_statement1;     
else if (<expression_2>) false_statement2;
else if (<expression_3>) false_statement3;  
else default_statement;

The <expression> is evaluated. If it is true (1 or a non-zero value), the true_statement is executed. However, if it is false (zero) or ambiguous (x), the false_statement is executed. The <expression> can contain any operators. Each true_statement or false_statement can be a single statement or a block of multiple statements. A block must be grouped, typically by using keywords begin and end, and A single statement need not be grouped as shown in example below.

// Type 1 statements
------------------------------------------------------ 
if (!lockbuffer = data; 
if (enableout = in;    
                                                    

// Type 2 statements
------------------------------------------------------ 2' 
if  (number_queued < MAX_Q_DEPTH)
  begin
      data_queue = data; 
       number_queued = number_queued + 1;
  end
else
      $display("Queue Full. Try again");


// Type 3 statements
// Execute statements based on ALU control signal.
------------------------------------------------------ 2'
if  (alu_control == 0)
      y = x + z; 
else if (alu_control == 1)
      y = x - z;
else if (alu_control == 2)
      y = x * z;
else 
      $display("Invalid ALU control signal");



Reference:
  • Verilog HDL, A guide to Digital Design and Synthesis, 2nd edtion, Samir Palnitkar, SunSoft Press - A Prentice Hall Title.
  • www.alanknox.net  (source of picture)

No comments:

Post a Comment