How to Swap Two Elements in a 2D Array in SystemVerilog
Breaking into the world of ASIC verification requires far more than a surface-level understanding of SystemVerilog or just crafting functional scripts. Leading semiconductor companies focus their interviews on how you approach complex problems, your grasp of underlying principles, and your familiarity with industry best practices. What might look like simple interview questions often serve as windows into your mindset for debugging, handling corner cases, and clearly articulating your solutions.
That’s exactly what inspired me to launch this blog series.The Simple, Naive Swap Function
Let's start with a basic swap function. This version skips safety checks and doesn't use
ref, making it easy to understand but unsafe// Naive swap (not robust)
function void simple_swap(byte arr[][], int i1, int j1, int i2, int j2);byte temp;temp = arr[i1][j1];arr[i1][j1] = arr[i2][j2];arr[i2][j2] = temp;endfunction
Problems in the Naive Version
- No boundary checks: Can crash simulation if indices are wrong
- Pass by value: The array isn't changed outside the function call.
- No debug info: Hard to verify in larger testbenches.
2. The Robust, Interview-Ready Swap Function
Now we upgrade the code for real projects and interviews, using ref and validation.
Now we upgrade the code for real projects and interviews, using ref and validation.
// Robust swap with checks and ref
function void swap_2d_elements(ref byte arr[][], int i1, int j1, int i2, int j2);
if (i1 >= arr.size() || i2 >= arr.size() || j1 >= arr[0].size() || j2 >= arr[0].size()) begin
$error("swap_2d_elements: Index out of bounds (%0d,%0d), (%0d,%0d)", i1, j1, i2, j2);
return;
end
byte temp = arr[i1][j1];
arr[i1][j1] = arr[i2][j2];
arr[i2][j2] = temp;
$display("Swapped arr[%0d][%0d] with arr[%0d][%0d]", i1, j1, i2, j2);
endfunction
Takeaways
- Start with simple code for clarity.
- Make your solution robust: use
refand validate indices. - Add debug output so others can quickly verify your logic.
- Explain these improvements in interviews—they prove your maturity as a verification engineer!

