Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

foreach Constraint Example 2

SystemVerilog Constraints

foreach constraints on both a dynamic array and a queue, with the queue sized by a separate constraint and the dynamic array sized in new().

Open in IDE
testbench.sv
//--------------------------------------------------------------
// Author  : Admin, ChipVerify
// Website : www.chipverify.com
//--------------------------------------------------------------

class ABC;
  rand bit[3:0] darray []; 		// Dynamic array -> size unknown
  rand bit[3:0] queue [$]; 		// Queue -> size unknown
  
  // Assign size for the queue if not already known
  constraint c_qsize  { queue.size() == 5; }
  
  // Constrain each element of both the arrays
  constraint c_array  { foreach (darray[i])    					  
    					  darray[i] == i;    					
                        foreach (queue[i]) 
                          queue[i] == i + 1;
                      } 
    function new ();
		darray = new[5]; 	// Assign size of dynamic array
	endfunction
endclass

module tb;
  
  initial begin
    ABC abc = new;
    abc.randomize();
    $display ("array = %p\nqueue = %p", abc.darray, abc.queue);
  end
endmodule



/*
Simulation Log:
---------------

ncsim> run
array = '{'h0, 'h1, 'h2, 'h3, 'h4}
queue = '{'h1, 'h2, 'h3, 'h4, 'h5}
ncsim: *W,RNQUIE: Simulation is complete.
ncsim> exit
*/
design.sv
// Code your design here
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.