Hi,
Can we use the Ternary operator in constraints, instead of if-else? I tried using Ternary but the result is not as expected.
Here is an example code:
class cons_check;
rand logic [1:0] a;
rand logic [3:0] b;
constraint cons{
solve a before b;
b == (a<2) ? 2 : 3;
//if (a<2) b == 2;
//else b == 3;
}
endclass
module tb();
cons_check cons_h = new();
initial begin
cons_h.randomize() with{a == 1;};
$display("a = %0d, b= %0d",cons_h.a, cons_h.b);
end
endmodule
Output with Ternary: a = 1, b= 10
Output with if-else: a = 1, b= 2
In reply to arrpaduru:
Your problem is the precedence of the equality ‘==’ operator is higher than the conditional operator ‘?:’. What you wrote gets interpreted as:
( b == (a<2) ) ? 2 : 3;
This leaves b unconstrained since any value of b results in the expression being non-zero(true).
In reply to dave_59:
Dave’s answer is not correct.
Correct constraint is
b == ((a<2) ? 2 : 3);
In reply to dave_59:
Hi Dave ,
(1) If ‘==’ takes precedence shouldn’t b be constrained to 1 since ( a < 2 ) would return 1 ( due to in-line constraint a == 1 ; )
(2) Also I didn’t get " since any value of b results in the expression being non-zero(true). "
What if I were to change constraint to ::
b == (a<2) ? 0 : 3;
Would the 0 ( since a == 1 ) play any part ?
Thanks .
In reply to MICRO_91:
When A is constrained to be 1
b == (a<2) ? 2 : 3;
⇩
b == 1 ? 2 : 3;
⇩
(b == 1) ? 2 : 3;
If the solver chooses b to be 1, then the result of this expression is 2, which satisfies the constraint because it is true (non-zero)
If the solver chooses b to a value other than 1, then the result of this expression is 3, which satisfies the constraint because it is true (non-zero)
The solver is free to choose any value for b.
If you change the constraint to
b == (a<2) ? 0 : 3;
⇩
b == 1 ? 0 : 3;
⇩
(b == 1) ? 0 : 3;
If the solver chooses b to be 1, then the result of this expression is 0, which does not satisfy the constraint because it is false (zero)
If the solver chooses b to a value other than 1, then the result of this expression is 3, which satisfies the constraint because it is true (non-zero).
So b is contrainted to be a value other than 1.
In reply to kitanisi:
You are not correct. Please look at table 11-2 in the 1800-2017 LRM and find which operators have higher precedence. You can also make s simple test case and plug in values for a and b.
$display (" the result of b == (a<2) ? 2 : 3 is %b", b == (a<2) ? 2 : 3. );
In reply to dave_59:
Thanks Dave for the detailed explanation .
(b == 1) is actually the condition ( for ternary operator ) rather than a equality constraint .