Tutorials
Learn More
foreach loop in constraint
Same as foreach loop, array constraints can also be implemented using foreach loop to iterate over array elements.
Syntax:
constraint <constraint_name> { foreach(variable[i]) variable[i] <condition>} foreach loop in constraint example
typedef enum {LOW, MID1, MID2, HIGH} scale;
class seq_item;
// Associative array indexed by the enum 'scale'
rand bit [7:0] value_a[scale];
rand bit [3:0] array[];
// Constructor to pre-allocate keys for the associative array
function new();
value_a[LOW] = 0;
value_a[MID1] = 0;
value_a[MID2] = 0;
value_a[HIGH] = 0;
endfunction
// Constraint for the dynamic array size
constraint arr_size_c { array.size() inside {[2:5]}; }
// Constraint for the dynamic array values
constraint array_c { foreach(array[i]) { array[i] > i*i; } }
// Constraint for the associative array values
constraint value_a_c {
foreach(value_a[i]) {
value_a[i] < 100;
(i == LOW) -> value_a[i] < 30;
(i == MID1) -> value_a[i] inside {[30:50]};
(i == MID2) -> value_a[i] inside {[51:70]};
(i == HIGH) -> value_a[i] > 70;
}
}
endclass
module constraint_example;
seq_item item;
initial begin
item = new();
repeat(5) begin
item.randomize();
foreach(item.value_a[i]) $display("value[%s] = %0d", i.name(), item.value_a[i]);
foreach(item.array[i]) $display("array[%0d] = %0d", i, item.array[i]);
end
end
endmodule Output:
value[LOW] = 7
value[MID1] = 49
value[MID2] = 61
value[HIGH] = 80
array[0] = 11
array[1] = 6
array[2] = 13
array[3] = 10
value[LOW] = 24
value[MID1] = 38
value[MID2] = 54
value[HIGH] = 80
array[0] = 4
array[1] = 9
array[2] = 7
value[LOW] = 11
value[MID1] = 39
value[MID2] = 61
value[HIGH] = 88
array[0] = 11
array[1] = 7
value[LOW] = 22
value[MID1] = 50
value[MID2] = 61
value[HIGH] = 90
array[0] = 15
array[1] = 2
array[2] = 6
value[LOW] = 17
value[MID1] = 43
value[MID2] = 67
value[HIGH] = 86
array[0] = 15
array[1] = 3 System Verilog Tutorials