Verilog: Control Statements

By using control statements, you can decide the order in which statements are executed.

if-else Conditional statements are used to decide which statement in a group of choices is executed. If a condition is evaluated to true, one statement is executed. If the condition evaluated to false, the else part of the code is executed.

module dut ( result, a , b ) ; output [3:0] result ; input [1:0] a , b ; reg [3:0] result ;

always@(*) begin if( a < b) result = 1 ; else if ( a > b ) result = 2 ; else if ( a >= b || a <= b ) result = 3 ; else result = 0 ; end endmodule

Testbench case statement case statement is a multiway decision statement. i.e. a number of values may be the evaluated value of the condition. You can implement case with if-else if as well.

module dut ( result, a , b ) ; output [3:0] result ; input [1:0] a , b ; reg [3:0] result ;

always@(*) begin case (a>b) 1 : result = 1 ; 0 : result = 2 ; default : result = 3 ; endcase end endmodule

Use the same testbench as above. forever forever continuously executes a statement. Most common example would be a simple clock generator.

module clock_model ( clk ) ; output clk ; reg clk ;

initial begin clk = 1'b0 ; forever begin #1 clk = ~clk; end end endmodule

repeat repeat repeats the statement a fixed number of time.

module repeat_loop () ; parameter count = 7 ; reg [6:0] result ;

initial begin repeat (count) begin result = result << 1 ; $display(" Result %b", result); end end endmodule

while loop The while loop repeats a statement until the condition becomes false.

module while_loop () ; reg [2:0] count ; reg [6:0] result ;

initial begin count = 2'b11; while (count) begin result = result << 1 ; count = count-1 ; $display("Result: %b, Count %b ", result, count); end end endmodule

for loop for loop has three parts separated by semicolon. First is an initialization statement, which initializes the variable that will control the loop. The second part is the condition in which the loop will be entered. Third part modifies the control variable after every loop entry.

module for_loop () ; reg [2:0] count ; reg [6:0] result ;

initial begin for (count=0; count <=3; count=count+1) begin result = result << 1 ; $display("Result: %b, Count %b ", result, count); end end endmodule