Menu
Coddy logo textTech

Comparison Operators

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

Comparison operators compare two values and return either 1 (true) or 0 (false).

Available Comparison Operators

OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal

Code Example

module comparison_demo;
  reg [3:0] a, b;
  reg result;
  
  initial begin
    a = 5;
    b = 3;
    
    result = (a == b);
    $display("5 == 3 : %d", result);  // 0 (false)
    
    result = (a != b);
    $display("5 != 3 : %d", result);  // 1 (true)
    
    result = (a > b);
    $display("5 > 3  : %d", result);  // 1 (true)
    
    result = (a < b);
    $display("5 < 3  : %d", result);  // 0 (false)
    
    result = (a >= 5);
    $display("5 >= 5 : %d", result);  // 1 (true)
    
    result = (a <= 3);
    $display("5 <= 3 : %d", result);  // 0 (false)
    $finish;
  end
endmodule

Output:

5 == 3 : 0
5 != 3 : 1
5 > 3  : 1
5 < 3  : 0
5 >= 5 : 1
5 <= 3 : 0

Using Comparisons in Conditions

Comparisons are often used in if statements:

if (count == 10)
  $display("Reached maximum");

if (value > threshold)
  $display("Value is too high");

Important Notes

  • Comparison results are 1-bit values (0 or 1)
  • Comparisons work with any bit width
  • Be careful with == and != when signals contain X or Z (they will return X)
challenge icon

Challenge

Write the correct comparison expressions for each task.

What to do:

  1. Check if a equals b and store in eq
  2. Check if a is greater than b and store in gt
  3. Check if a is less than or equal to b and store in le

Cheat sheet

Comparison operators in Verilog compare two values and return 1 (true) or 0 (false).

OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal

Comparisons are commonly used in if statements:

if (count == 10)
  $display("Reached maximum");

if (value > threshold)
  $display("Value is too high");

Note: Results are 1-bit values. Using == or != with signals containing X or Z will return X.

Try it yourself

module comparison_challenge;
  reg [3:0] a, b;
  reg eq, gt, le;
  
  initial begin
    a = 4'd7;
    b = 4'd7;
    
    eq = ______;   // a equals b
    gt = ______;   // a greater than b
    le = ______;   // a less than or equal to b
    
    $display("a = %d, b = %d", a, b);
    $display("a == b : %d", eq);
    $display("a > b  : %d", gt);
    $display("a <= b : %d", le);
    $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