Multiple arguments to foreach loop

class packet;
 rand bit [7:0] x[10];
 rand bit [7:0] y[10];
 rand bit [7:0] width;

  constraint x_y_width { foreach[] {x[i] + y[i] < width};}

endclass

I want sum of respective element of x with y and it should be less than width.
I mean x[0] + y[0] < width;
x[1] + y[1] < width; and so on …

How to write multiple arguments to foreach loop?
I have kept argument to foreach loop blank in above.

In reply to DhavalP:
A foreach loop just gives you an index to iterate over, just like a for loop. Within the loop, you can do whatever you want with the index value.

  constraint x_y_width { foreach(x[i]) {x[i] + y[i] < width};}

In reply to dave_59:

Hi Dave,

It is not giving proper output. I have tried as below. I have also constraint width to small value for easy calculation.

Code::

class packet;
 rand bit [7:0] x[10];
 rand bit [7:0] y[10];
 rand bit [7:0] width;

  constraint x_y_width { foreach(x[i]) {x[i] + y[i] < width};                                  width<15;}

endclass

module packet_m;
  packet pkt;
  initial begin
    pkt=new();
    pkt.randomize();
    $display("x=%0p,y=%0p,pkt.width=%0d",pkt.x,pkt.y,pkt.width);
  end
  
endmodule

Output::

x='{'h8c, 'h28, 'ha, 'haa, 'h35, 'h6f, 'h5c, 'h10, 'h94, 'hbf} ,y='{'h7d, 'he2, 'hf6, 'h5f, 'hce, 'h95, 'hac, 'hf5, 'h71, 'h4c} ,pkt.width=13

In reply to DhavalP:
BTW, Please use code tags making your code easier to read. I have added them for you.

You are getting the proper output for the constraints you wrote. It’s just that you didn’t write the proper constraint for the output you intended to see. :smiling_face:

Read this and try:

constraint x_y_width { foreach(x[i]) int’(x[i] + y[i]) < width;
                       width<15; }

In reply to dave_59:

Is this kind of static casting?

int’{x[i] + y[i])

In reply to DhavalP:

Yes, but I had a typo with one of my parentheses that I just corrected.