Tutorials

Learn More

Based on the If-else condition, values for the variable can be assigned. It is similar to a normal if-else condition.

Example for if-else

class seq_item;
  rand bit [7:0] value;
  rand enum {LOW, HIGH} scale;

  constraint scale_c { if(scale == LOW) value < 50;
                       else value >= 50;
                     }
endclass

module constraint_example;
  seq_item item;
  
  initial begin
    item = new();
    
    repeat(5) begin
      item.randomize();
      $display("scale = %s, value = %0d", item.scale.name(), item.value);
    end
  end
endmodule

Output:

scale = LOW, value = 17
scale = LOW, value = 43
scale = HIGH, value = 83
scale = HIGH, value = 61
scale = HIGH, value = 194

Example for if-else if-else

class seq_item;
  rand bit [7:0] value;
  rand enum {LOW, MID, HIGH} scale;

  constraint scale_c { if(scale == LOW) value < 30;
                       else if(scale == MID) { value >= 30; value <= 70; }
                       else value > 70;
                     }
endclass

module constraint_example;
  seq_item item;
  
  initial begin
    item = new();
    
    repeat(10) begin
      item.randomize();
      $display("scale = %s, value = %0d", item.scale.name(), item.value);
    end
  end
endmodule

Output:

scale = HIGH, value = 146
scale = LOW, value = 11
scale = HIGH, value = 117
scale = MID, value = 46
scale = HIGH, value = 139
scale = LOW, value = 27
scale = HIGH, value = 92
scale = HIGH, value = 201
scale = HIGH, value = 146
scale = MID, value = 48

Example for the conditional operator

class seq_item;
  rand bit [7:0] value;
  rand enum {LOW, HIGH} scale;

  constraint scale_c { value == ((scale == LOW) ? 20: 90); }
endclass

module constraint_example;
  seq_item item;
  
  initial begin
    item = new();
    
    repeat(5) begin
      item.randomize();
      $display("scale = %s, value = %0d", item.scale.name(), item.value);
    end
  end
endmodule

Output:

scale = LOW, value = 20
scale = LOW, value = 20
scale = LOW, value = 20
scale = HIGH, value = 90
scale = LOW, value = 20

System Verilog Tutorials