Blog#3 - Constraint to generate an array of numbers that add up to 17, with at least one number being a multiple of 4
Introduction
As an ASIC verification engineer, you'll often deal with array constraints in SystemVerilog—especially when prepping for interviews. Modern tools make it easy to specify powerful properties with reduction methods, but small details like type casting can make all the difference between working code and puzzling bugs.
Interview Question
Constraint to generate an array of numbers that add up to 17, with at least one number being a multiple of 4.
Let me show you how I'd write this in SystemVerilog using array reduction expressions:
class my_array_class;rand int my_arr[5];// Constraint: sum of items is 17constraint c3 { my_arr.sum() with (int'(item)) == 17; }// Constraint: at least one item is a multiple of 4constraint c4 { my_arr.or() with (int'(item % 4)) == 1; }endclass
Here,c3makes sure the array adds up to 17, andc4ensures at least one value in the array is a multiple of 4.
Why is int' Needed in These Constraints?
A lot of folks—even experienced engineers—gloss over the cast (int'(item)) thinking it's optional. But it plays a VERY important role:
Type safety: If your array is made of
byte,shortint, or another small-width type, the reduction (likesum()) could accidentally wrap or overflow. The cast ensures every item is treated as a 32-bit signedintbefore summing or evaluating modulo.Consistency: With explicit casting, you get the same calculation regardless of how you declare
my_arr.Simulator compatibility: Some tools are picky and expect types to match in reduction methods—casting avoids warnings and errors.
Professional coding: Using
int'makes your code robust, clear, and future-proof during interviews or code reviews.
Quick Example: Without casting, summing large positive byte values could wrap past 127 or become negative. With int'(item), you always get the intended integer sum.
Takeaway: Whenever you’re using SystemVerilog reduction methods in constraints—especially in interviews—cast your item to int unless you are absolutely sure the type will never cause trouble. It’s the difference between “I hope it works” and “I KNOW it works.”
If you're interested in more blogs like this, please subscribe to learnchipdesign.comlearnchipdesign.wordpress.com for regular updates, practical tips, and in-depth interview preparation!

