Menu
Coddy logo textTech

If - Else

Part of the Fundamentals section of Coddy's Verilog journey — lesson 53 of 90.

The if-else statement allows you to choose between two different actions based on a condition. If the condition is true, one block executes. If false, the other block executes.

The if-else statement gives your code a decision point: do one thing if the condition is true, do another thing if the condition is false.

Syntax:

if (condition) begin
  // Executes when condition is true (1)
end else begin
  // Executes when condition is false (0)
end

Simple Example

if (reset) begin
  count = 0;
end else begin
  count = count + 1;
end
  • If reset is 1 → count becomes 0
  • If reset is 0 → count increases by 1

Multiple Statements

Use begin and end when you have more than one statement:

if (enable) begin
  out = data_in;
  valid = 1;
end else begin
  out = 0;
  valid = 0;
end

If-Else with Multiple Conditions

You can chain if-else statements:

if (a > b) begin
  max = a;
end else if (b > a) begin
  max = b;
end else begin
  max = a;  // a and b are equal
end

Important Rules

RuleExplanation
else is optionalYou can have if without else
else belongs to the nearest ifBe careful with nesting
Use begin/end for multiple statementsRequired for more than one line
challenge icon

Challenge

What to do:

  1. Add the missing if-else statement to make this work.
  2. When enable is 1, out should equal a & b.
  3. When enable is 0, out should equal a | b.

Cheat sheet

The if-else statement executes one of two blocks based on a condition:

if (condition) begin
  // Executes when condition is true (1)
end else begin
  // Executes when condition is false (0)
end

Chain multiple conditions with else if:

if (a > b) begin
  max = a;
end else if (b > a) begin
  max = b;
end else begin
  max = a; // a and b are equal
end
  • else is optional
  • Use begin/end when multiple statements are in a block
  • else always belongs to the nearest if

Try it yourself

module ifelse_challenge;
  reg a, b, enable;
  reg out;
  
  initial begin
    a = 1;
    b = 0;
    enable = 1;
    
    // TODO: Add if-else statement
    // If enable is 1: out = a & b
    // Else: out = a | b
    
    $display("out = %d (should be 0 because 1&0=0)", out);
    $finish;
  end
endmodule
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals