Constraint on sum of the array elements without using the pre-defined array method sum

Hello,

I want to apply the constraint on the sum of the array elements without using the pre-defined array method sum.

I am using below code :

**class random;
rand int a;

function int sum();
int temp = 0;
foreach(a[i])
begin
temp = temp + a[i];
$display(“Sum : a[%0d] = %0d”,i,a[i]);
end
return temp;
endfunction

constraint a_size {a.size == 10;};
constraint a_value {foreach(a[i]) a[i] inside {[0:10]};
// a.sum == 10 // other than this method
sum() == 10;
};
endclass

program check;
initial
begin
random r = new();
r.randomize();
foreach(r.a[i])
$display(“A[%0d] = %0d”,i,r.a[i]);
end

endprogram**

Here, the problem I am facing is simulator is not allowing pass the array by reference to user defined method sum, apart from this I have also tried to use class member array directly inside the function sum, it is also giving error like, rand variable can’t be used inside constraint function.

This is just for experiment I am not sure whether we can do this or not.

Can anyone give any advice on this?

Simulator I am using is VCS.

Thanks for your answer!

In reply to nikulsavaliya07:

Hi nikulsavaliya07. Section 18.5.12 of the 1800-2012 LRM addresses this, which states that “Functions shall be called before constraints are solved, and their return values shall be treated as state variables.”

Your constraint

constraint a_value {foreach(a[i]) a[i] inside {[0:10]}; sum() == 10;};

violates this, since the sum() method is returning a value that depends on the contents of a. However some built-in functions / methods are allowed, such as array reduction methods (a.sum() in this case). See Using Function Inside Constraint - is this LRM Compliant? | Verification Academy for more information on that.