I have an array in which odd numbers should be present in even indices and even numbers should be present in odd indices with using “%” operator.
//CODE
class ex;
rand bit[3:0] a[10];
rand bit [3:0] j;
constraint c{
foreach(a[i]){
a[i] inside {[0:15]};
if(i & 4’b0001 == 1){ // For odd indices
a[i] & 4’b0001 == 0; // LSB should be 0
}
else { // For even indices
a[i] & 4’b0001 == 1; // LSB should be 1
}
}
}
endclass
module tb;
ex e;
initial begin
e = new();
void’(e.randomize());
$display(“a=%p”, e.a);
end
endmodule
for the above code I am getting constraint conflicts, can anyone please help me with this issue
actually I tried by writing like below (writing the AND operation inside brackets):
class ex;
rand bit[3:0] a[10];
constraint c{
foreach(a[i]){
a[i] inside {[1:15]};
if(i & 4’b0001 == 1){ // For odd indices
(a[i] & 4’b0001) == 0; // LSB should be 0 // ----------------------> (1)
}
else { // For even indices
a[i] & 4’b0001 == 1; // LSB should be 1------------------------------> (2)
}
}
}
endclass
If I give brackets for (1) its working, but for (2) its working without brackets also. Can someone please explain me this
Try this it will work !!!
class ex;
rand bit[3:0] a[10];
rand bit [3:0] j;
constraint c{
foreach(a[i]){
a[i] inside {[0:15]};
if(i % 2 == 1){ // For odd indices
(a[i] & 4'b0001) == 0; // LSB should be 0
}
else { // For even indices
(a[i] & 4'b0001) == 1; // LSB should be 1
}
}
}
function string display ();
foreach(a[i])
$display ("i=%0d a[i]=%d", i,a[i]);
endfunction
endclass
module tb;
ex e;
initial begin
e = new();
e.randomize();
e.display();
end
endmodule
problem is with ‘precedence order’. The issue in your code arises from the way you are using the bitwise AND operator (&
) and the equality operator (==
).
Arithmetic operator (Highest precedence) → Relational operator → equality operator → reduction operator → logical operator → conditional operator (Lowest precedence).
- Arithmetic operators:
+
, -
, *
, /
, %
- Relational operators:
<
, <=
, >
, >=
- Equality operators:
==
, !=
, ===
, !==
- Bitwise operators:
&
, |
, ^
, ~
- Logical operators:
&&
, ||
, !
- Conditional operator:
? :
corrected code:
class ex;
rand bit [3:0] a[10];
rand bit [3:0] j;
constraint c {
foreach(a[i]) {
a[i] inside {[0:15]};
if (i % 2 == 0) { // For even indices
a[i][0] == 1; // LSB should be 1 (odd number)
} else { // For odd indices
a[i][0] == 0; // LSB should be 0 (even number)
}
}
}
endclass