Gotcha: Using a==b==c in SystemVerilog Constraints

Looking over verification forums, I found a thread where the author was wondering how does a==b==c constraint get evaluated since the result was not the one he was expecting.

The scenario is like this: three variables need to be randomized and you want to constraint them to the same value. If you are thinking to use the a==b==c expression, like in the code below, you’ll find out that this is not a good idea.

class abc;
  rand int unsigned a,b,c;
  constraint abc_constr{

module top;
  initial begin
    abc abc_inst = new();
      $display("a = %0d, b = %0d, c = %0d", abc_inst.a, abc_inst.b, abc_inst.c);
      $display("ERR: Could not randomize abc_inst");

This example will run without error (i.e. the randomization succeeded) although the three variables are not equal! For example, one of the runs generated following values: a=416024649, b=2651484123, c=0 without any error.

Furthermore, if you want to constraint them to a certain value and you choose to constraint c to that specific value…again, you’ll discover that randomization fails:

if(abc_inst.randomize() with {
  $display("a=%0d, b=%0d, c=%0d", abc_inst.a, abc_inst.b, abc_inst.c);
  $error("Could not randomize abc_inst");

If you run the example above you get Could not randomize abc_inst message.

How can you explain this behaviour? Well, in order to get the constraint satisfied, expression a==b==c should be evaluated TRUE. The “Gotcha” is: due to == binary operator, the expression is evaluated from left to right, as follows:

  • a==b – if a has the same value as b then the result of the evaluation is 1, otherwise the result is 0
  • (a==b)==c – in order to make the hole expression TRUE, then c will have to be equal to the result of a==b evaluation, meaning that if a is different from b, c will have the value 0, otherwise it will have the value 1.

This means that c will always be either 0 or 1, such that the only set of values that satisfy a==b==c is all 1’s.

The workaround is to split the expression in two separate constraints:

constraint abc_constr{

The variables will get the same value; it also works in case c is constrained to a certain value.

Another “Gotcha” is busted!


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe to our newsletter

Do you want to be up to date with our latest articles?