Fpga Insights

Mastering SystemVerilog Arrays: A Comprehensive Guide

Niranjana R

December 27, 2023

Table of Contents

Introduction

Welcome to “Mastering SystemVerilog Arrays: A Comprehensive Guide.” In the realm of hardware design and verification, SystemVerilog stands out as a powerful language, and understanding its array of capabilities is crucial for harnessing its full potential. Arrays in SystemVerilog offer a versatile and efficient way to manage data, making them a fundamental aspect of hardware description and verification languages.

A. Brief Overview of SystemVerilog

SystemVerilog, an extension of Verilog, was developed to address the challenges of modern hardware design and verification. It encompasses features that facilitate concise and readable code, making it a preferred language in the semiconductor industry. The language not only supports traditional hardware description but also incorporates powerful constructs for verification, making it an ideal choice for verification engineers.

B. Importance of Arrays in SystemVerilog

Arrays serve as a cornerstone in SystemVerilog programming, offering a structured and efficient means of handling data. Whether dealing with large datasets, complex algorithms, or dynamic data structures, arrays provide the flexibility needed to navigate the intricacies of hardware design and verification. This guide aims to unravel the intricacies of SystemVerilog arrays, from their basic definitions to advanced usage scenarios.

Now, let’s delve into the fundamental concepts of SystemVerilog arrays, exploring their declaration, initialization, and basic operations.

SystemVerilog Array Basics

A. definition and declaration of arrays.

In SystemVerilog, arrays are variables that can store multiple values of the same data type. Before delving into their usage, it’s essential to understand how to declare them. The syntax for declaring an array involves specifying the data type, array name, and size.

1. Syntax for Array Declaration

// Syntax: data_type array_name[size];
bit [7:0] byte_array[255]; // Example declaration of a byte array with 256 elements

2. Data Types Supported for Arrays

SystemVerilog supports a variety of data types for arrays, including built-in types like bit, logic, and user-defined types. This flexibility allows for the creation of arrays tailored to specific design requirements.

B. Initialization of Arrays

Once declared, arrays can be initialized either explicitly or implicitly. Explicit initialization involves specifying values during declaration, while implicit initialization relies on default values.

1. Explicit Initialization

bit [3:0] nibble_array[4] = ‘{4’b0000, 4’b0011, 4’b1100, 4’b1111};

2. Implicit Initialization

Implicit initialization initializes all elements to their default values based on the data type.

logic [7:0] data_array[10]; // All elements initialized to ‘0’

Understanding these basic concepts sets the foundation for further exploration into array indexing, slicing, and the dynamic aspects of arrays in SystemVerilog, which we’ll delve into in the next section.

Array Indexing and Slicing

A. understanding array indexing.

Array elements in SystemVerilog are accessed using indices, and it’s crucial to grasp the indexing conventions. SystemVerilog uses zero-based indexing, meaning the first element of an array has an index of 0. For multi-dimensional arrays, indices are specified for each dimension.

1. Zero-Based Indexing

logic [3:0] data_array[7]; // Array with indices 0 to 7
data_array[0] = 4’b1010;   // Accessing the first element

2. Multi-Dimensional Arrays

bit [1:0] matrix[3][2]; // 3×2 matrix
matrix[2][1] = 2’b10;   // Accessing an element in a multi-dimensional array

B. Slicing Techniques

Array slicing allows the extraction of a subset of elements from an array. This can be particularly useful when working with large datasets or when specific portions of an array need to be manipulated.

1. Basic Slicing

logic [7:0] data_array[15];
logic [3:0] subset_array[4];

subset_array = data_array[7:4]; // Extracting elements 7 to 4 from data_array

2. Advanced Slicing for Multidimensional Arrays

bit [7:0] matrix[3][3];
bit [3:0] column_subset[3];

column_subset = matrix[1:3][2]; // Extracting the entire second column from the matrix

Understanding array indexing and slicing lays the groundwork for exploring dynamic arrays and associative arrays, which offer even greater flexibility in handling data in SystemVerilog. In the following sections, we’ll delve into these advanced array types and their applications.

Dynamic Arrays in SystemVerilog

A. introduction to dynamic arrays.

Dynamic arrays in SystemVerilog provide a flexible alternative to fixed-size arrays. Unlike static arrays, dynamic arrays don’t require a predefined size during declaration, allowing for dynamic allocation and resizing during runtime.

B. Dynamic Array Methods and Functions

1. Using the “new” Keyword

The new keyword is employed to dynamically allocate memory for a dynamic array. This enables the creation of arrays without specifying a fixed size at compile time.

logic [] dynamic_array;

// Dynamically allocating memory for the dynamic array
dynamic_array = new[10];

2. Resizing Arrays

Dynamic arrays can be resized during runtime using the $resize system task. This task allows the array to grow or shrink as needed.

// Resizing the dynamic array to accommodate 20 elements
$resize(dynamic_array, 20);

Understanding the dynamics of dynamic arrays opens the door to more adaptive data structures in SystemVerilog. However, when it comes to associative arrays, SystemVerilog offers a unique and powerful tool for handling complex data relationships.

Associative Arrays in SystemVerilog

A. definition and purpose of associative arrays.

Associative arrays, also known as “hash” or “unordered” arrays, differ from traditional arrays in that they use keys instead of indices to access elements. This makes them particularly useful for scenarios where the relationship between data points is not strictly sequential.

B. Operations on Associative Arrays

1. Adding and Removing Elements

// Declaration of an associative array
int associative_array[string];

// Adding elements to the associative array
associative_array[“apple”] = 5;
associative_array[“banana”] = 8;

// Removing an element
associative_array.delete(“apple”);

2. Iterating Through Associative Arrays

foreach (associative_array[key]) begin
    // Accessing each element in the associative array
    $display(“Key: %s, Value: %0d”, key, associative_array[key]);
end

As we explore associative arrays, we’ll uncover their usefulness in various applications, from handling configuration data to efficiently managing complex data relationships in verification environments.

In the upcoming sections, we’ll delve into practical array manipulation techniques, including sorting and searching arrays, and showcase real-world examples of SystemVerilog array usage. Understanding these advanced topics will empower you to leverage arrays effectively in your hardware design and verification projects.

SystemVerilog Array Manipulation

A. sorting arrays.

1. Using Built-in Sorting Functions

SystemVerilog provides convenient built-in functions for sorting arrays. The $sort function simplifies the process of arranging elements in ascending or descending order.

logic [7:0] data_array[10];
$sort(data_array); // Sorting data_array in ascending order

2. Implementing Custom Sorting Algorithms

For more complex sorting requirements, custom sorting algorithms can be implemented. Understanding algorithms like quicksort or mergesort allows for tailored solutions.

// Example: Quicksort implementation for sorting an integer array
function void quicksort(int array[], int low, int high);
    // Implementation details
endfunction

// Sorting an array using the custom quicksort algorithm
quicksort(data_array, 0, data_array.size() – 1);

B. Searching Arrays

1. Linear Search

Linear search is a straightforward method for finding an element in an array. It involves traversing the array sequentially until the target element is located.

logic [3:0] data_array[8] = ‘{4, 7, 2, 9, 1, 5, 8, 3};
int target = 5;
int index = -1;

// Performing a linear search
for (int i = 0; i < data_array.size(); i++) begin
    if (data_array[i] == target) begin
        index = i;
        break;
    end
end

2. Binary Search

Binary search is a more efficient search algorithm but requires a sorted array. It involves repeatedly dividing the search range in half until the target is found.

logic [3:0] sorted_array[8] = ‘{1, 2, 3, 4, 5, 7, 8, 9};
int target = 5;
int index = -1;

// Performing a binary search
int low = 0, high = sorted_array.size() – 1;
while (low <= high) begin
    int mid = (low + high) / 2;
    if (sorted_array[mid] == target) begin
        index = mid;
        break;
    end
    if (sorted_array[mid] < target)
        low = mid + 1;
    else
        high = mid – 1;
end

Mastering array manipulation techniques like sorting and searching is crucial for optimizing performance in hardware design and verification scenarios. In the next section, we’ll explore real-world examples of SystemVerilog array usage, demonstrating how these techniques can be applied in practical situations.

Array Usage in Real-world Examples

A. case studies.

1. Verifying Complex Hardware Designs

In the realm of hardware verification, arrays play a pivotal role in managing test vectors, tracking signals, and validating circuit behavior. Consider a scenario where an intricate hardware design involves multiple registers with varying configurations. An array can efficiently store and manipulate these configurations, simplifying the verification process.

// Example: Storing register configurations in a dynamic array
bit [7:0] register_configs[][3];

// Adding register configurations
register back(‘{8’h01, 8’hFF, 8’hA5});
register back(‘{8’h0F, 8’h00, 8’h55});

// Accessing a specific register configuration
bit [7:0] config = register_configs[1][2]; // Accessing the third element of the second configuration

2. Handling Testbench Data with Arrays

In a testbench environment, arrays can be instrumental in managing stimulus data, response checking, and coverage tracking. Consider a testbench scenario where different test cases are generated and executed. Arrays can store the test cases and their corresponding expected outcomes, facilitating efficient testbench automation.

// Example: Storing test cases and expected outcomes in associative arrays
int test_cases[string];
int expected_results[string];

// Adding test cases
test_cases[“Test1”] = 10;
test_cases[“Test2”] = 25;

// Running tests and checking results
foreach (test_cases[tc]) begin
    int result = run_test(tc);
    if (result == expected_results[tc])
        $display(“Test %s Passed”, tc);
    else
        $display(“Test %s Failed”, tc);
end

By examining these case studies, it becomes evident how SystemVerilog arrays can streamline complex processes in hardware design and verification.

In this comprehensive guide, we have embarked on a journey to master SystemVerilog arrays, unraveling their intricacies and exploring their myriad applications in hardware design and verification. From the fundamental concepts of array declaration, initialization, and indexing to advanced topics like dynamic arrays and associative arrays, we’ve covered the spectrum of array-related features that SystemVerilog offers.

Understanding the power of SystemVerilog arrays is crucial for harnessing the language’s capabilities in handling diverse data structures, managing complex hardware designs, and creating efficient testbenches. The ability to manipulate arrays through sorting, searching, and dynamic allocation provides engineers with the tools needed to optimize performance and streamline their coding practices.

The real-world case studies showcased the practical application of SystemVerilog arrays in scenarios ranging from complex hardware designs with multiple configurations to automated testbenches handling diverse test cases. These examples highlight how arrays can enhance readability, maintainability, and efficiency in real-world projects.

As we conclude this guide, it is essential to emphasize the significance of best practices in SystemVerilog array usage. By optimizing performance, writing readable and maintainable code, and handling large data sets with efficiency, engineers can ensure that their array-based implementations contribute to robust and reliable hardware designs.

Related Articles

VERILOG ARRAY UNDERSTANDING AND IMPLEMENTING ARRAYS IN VERILOG

1 thought on “Mastering SystemVerilog Arrays: A Comprehensive Guide”

What fundamental concepts of SystemVerilog arrays does the article aim to explore, including aspects such as declaration, initialization, and basic operations? regard Telkom University

Leave a Comment

PCI Express 3.0 (1)

most recent

array assignment in system verilog

Artificial Intelligence

Ai in music: creating innovative compositions and personalized playlists.

array assignment in system verilog

AI in Financial Services – Revolutionizing Banking and Investment Strategies

array assignment in system verilog

Test & Measurement

Integrating test & measurement in agile development: best practices.

array assignment in system verilog

Automated Testing for Drone Technology: Ensuring Safe Flights

array assignment in system verilog

Power Management

Power management in high-performance computing (hpc) systems.

array assignment in system verilog

Power Management Strategies for Remote and Off-Grid Locations

Subscribe to get our best viral stories straight into your inbox, related posts.

  • Verilog Array: Understanding and Implementing Arrays in Verilog December 3, 2023
  • Unleashing the Potential of SystemVerilog Dynamic Arrays: Guide to Optimise Code January 18, 2024
  • Loops in Verilog: A Comprehensive Guide November 23, 2023
  • Unlocking the Power of Verilog While Loop: Optimizing Performance and Streamlining Design January 18, 2024
  • Verilog Generate: Guide to Generate Code in Verilog December 3, 2023
  • Achieving Proficiency in SystemVerilog Tasks: A Comprehensive Guide for Excellence December 20, 2023

array assignment in system verilog

FPGA Insights have a clear mission of supporting students and professionals by creating a valuable repository of FPGA-related knowledge to contribute to the growth and development of the FPGA community and empower individuals to succeed in their projects involving FPGAs. FPGA Insights has been producing FPGA/Verilog/VHDL Guides and blogs with the aim of assisting students and professionals across the globe. The mission of FPGA Insights is to continually create a growing number of FPGA blogs and tutorials to aid professionals in their projects.

© 2024 Fpga Insights. All rights reserved

Beyond Circuit Podcast by Logic Fruit: High-speed video interfaces in Indian Aerospace & Defence.

SystemVerilog Multidimensional Arrays

array assignment in system verilog

You asked and I listened

Thank you everyone who registered and attended my webinar on SystemVerilog arrays . There were many great questions and I’ve answered many of them  here . “SystemVerilog arrays” is a big topic and I had to leave out many ideas. There were several questions on Multidimensional Arrays (MDAs), so here is a very short introduction. Copy and paste this code and run on your favorite simulator. Get dirty, make mistakes, debug – you are a verification engineer so figure it out!

Exploring the next dimension

Let’s start with a one dimensional array, fixed size, with 4 elements and some code to initialize it.

The best way to think about MDAs is that they are arrays of arrays. So a two dimensional array like the following is made of 3 arrays, each which has 4 elements.

array assignment in system verilog

Here is its layout in memory.

array assignment in system verilog

You can assign three copies of the one array to it.

Stepping through MDAs

By now you know that my favorite way to step through an array is with a foreach loop. SystemVerilog has a quirk here – the foreach has a comma separated list of index variables, not separate bracketed indexes. Here is an example.

Here is the output. You can see that the right-most dimension varies the fastest.

Hip to be (not) square

You can mix array types with MDAs. How about a fixed size array that contains several dynamic arrays? Better yet, the dynamic arrays don’t have to be the same size, so the final array could be triangular!

Scoreboard with multiple matches

When you are building a testbench, your scoreboard needs to save the expected results until they are compared with the actual values from the design. If it can reorder transactions, you can store transactions in an associative array so you can easily look them up, based on a key value that won’t change as the transaction moves through the system. For example, there might be an address field, so store the transactions in an associative array indexed by the address.

That works well until two transactions have the same address, so they both need to be stored in the same location in the associative array, which is not possible. So instead, make every element a queue of all the transactions with that single address. I’ve been saying this for decades, but never actually did this. Turns out to be trivial! First, here is a simplified version with just integers.

Now here is a more elaborate example. The transaction class has address and data properties. If you construct an object with new(12), the constructor splits the value into the 10’s and the 1’s digits, so the data is 10 and the address is 2.

Here is the scoreboard and a temporary handle, and a function to add an element.

Finally, the following code fills the scoreboard with the transactions for the values 0, 1, 2, … 21.

Try this out with your favorite simulator, especially if it starts with Q.

Enjoy your verification journey! Chris Spear

Keep learning at mentor.com/training Questions or ideas? verificationacademy.com/ask-chris-spear View my recent webinar on SystemVerilog arrays  and the Questions and Answers

What to read next:

In Memoriam: Chris Spear

  • Pingback: Blog Review: June 17

Leave a Reply Cancel reply

You must be logged in to post a comment.

Verilog Pro

Verilog Arrays Plain and Simple

Arrays are an integral part of many modern programming languages. Verilog arrays are quite simple; the Verilog-2005 standard has only 2 pages describing arrays, a stark contrast from SystemVerilog-2012 which has 20+ pages on arrays. Having a good understanding of what array features are available in plain Verilog will help understand the motivation and improvements introduced in SystemVerilog. In this article I will restrict the discussion to plain Verilog arrays, and discuss SystemVerilog arrays in an upcoming post.

Verilog Arrays

Verilog arrays can be used to group elements into multidimensional objects to be manipulated more easily. Since Verilog does not have user-defined types, we are restricted to arrays of built-in Verilog types like nets, regs, and other Verilog variable types.

Each array dimension is declared by having the min and max indices in square brackets. Array indices can be written in either direction:

Personally I prefer the array2 form for consistency, since I also write vector indices (square brackets before the array name) in [most_significant:least_significant] form. However, this is only a preference not a requirement.

A multi-dimensional array can be declared by having multiple dimensions after the array declaration. Any square brackets before the array identifier is part of the data type that is being replicated in the array.

The Verilog-2005 specification also calls a one-dimensional array with elements of type reg a memory . It is useful for modeling memory elements like read-only memory (ROM), and random access memory (RAM).

Verilog arrays are synthesizable, so you can use them in synthesizable RTL code.

Assigning and Copying Verilog Arrays

Verilog arrays can only be referenced one element at a time. Therefore, an array has to be copied a single element at a time. Array initialization has to happen a single element at a time. It is possible, however, to loop through array elements with a generate or similar loop construct. Elements of a memory must also be referenced one element at a time.

Verilog arrays are plain, simple, but quite limited. They really do not have many features beyond the basics of grouping signals together into a multidimensional structure. SystemVerilog arrays, on the other hand, are much more flexible and have a wide range of new features and uses. In the next article— SystemVerilog arrays, Synthesizable and Flexible —I will discuss the new features that have been added to SystemVerilog arrays and how to use them.

  • 1364-2005 – IEEE Standard for Verilog Hardware Description Language

Sample Source Code

The accompany source code for this article is a toy example module and testbench that illustrates SystemVerilog array capabilities, including using an array as a port, assigning multi-dimensional arrays, and assigning slices of arrays. Download and run it to see how it works!

[lab_subscriber_download_form download_id=11].

Share this:

  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Pocket (Opens in new window)
  • Click to email a link to a friend (Opens in new window)
  • Click to print (Opens in new window)

14 thoughts on “Verilog Arrays Plain and Simple”

In the initial array_name example, don’t you have the msb and lsb swapped around?

Hi Graham. You’re right! I’ve fixed the typo. Thanks for noticing the error.

what to do if i want to copy an array content to other array? Is using a loop the only way to do so ?

Hi Priyansh. With plain Verilog-2005, yes that is the only way to do it. With SystemVerilog you can manipulate arrays much more easily, like copying slices, dimensions, entire arrays. See my post SystemVerilog Arrays, Flexible and Synthesizable .

If there’s no difference between array1[0:7] and array2[7:0], why does one have to put the lsb and msb?

Hi Stefan. I think internally depending on which way you define the array, it does potentially affect the location of where the data is placed (e.g. where array1[0] is located). But that will be transparent you when coding RTL as long as you use the indices consistently. SystemVerilog actually allows you to define an array with just array1[SIZE], which is the same as array1[0:SIZE-1].

I have a doubt regarding 2D arrays in Verilog. Suppose I want a design which take two 2D arrays as inputs and gives an output as 2D array. When I tried to declare the input output ports as 2D arrays, it did not work at all. I request you to kindly suggest me the way i can do my above said task in verilog.

Thanks in Advance…..

Hi. See an example I created on edaplayground here .

Hi Jason, I want to instantiate FIFO block 256 times. How to write an array?

Thanks In Advance

Hi Chetana. If you want to instantiate a module multiple times in an array, you need to use a generate loop. See my article Verilog Generate Configurable Designs .

Hi sir..how can i form covariance matrix in verilog.sir please suggest coding.

Hi Jason, I have a question regarding arrays and memory. I want to write the content of a 1D array into a specific location of a memory. But I’m not able to do this for some reason. I request you to kindly suggest me the way i can do my above said task in verilog.

Thanks in Advance…

Hi Gautham. Sorry I don’t fully understand your question. A 1D array has multiple elements. How can you write that into one location of a memory? Or you mean you want to write it to multiple consecutive locations of the memory?

Hi Jason. Thank you for replying back. I’m sorry that the question is not very clear. Yes, I wanted to ask how to write data from a 1D array into consecutive locations of a memory in verilog.

Thank you…

Leave a Comment Cancel reply

Notify me of follow-up comments by email.

Notify me of new posts by email.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

SystemVerilog Dynamic Arrays and Queues

In this post, we talk about the different types of dynamic arrays we can use in SystemVerilog, including normal dynamic arrays and their associated methods , queues and their associated methods and finally associative arrays .

As we talked about in a previous post, we can declare either static or dynamic arrays in SystemVerilog.

When we declare a static array, a fixed amount of  memory is allocated  to the array at  compile time . We have discussed SystemVerilog static arrays in depth in a previous blog post.

In contrast, we can allocate extra memory or resize a dynamic array while a simulation is running. As a result of this, we can only use dynamic arrays in our testbench code and not in synthesizable code.

In the rest of this post we talk about the way we can use dynamic arrays in our SystemVerilog code.

There are actually three different types of dynamic array which we can use in SystemVerilog - dynamic arrays, queues and associative arrays.

We use each of these three types of array to perform a slightly different task in our testbench. We discuss all three of these arrays in more detail int he rest of this post

SystemVerilog Dynamic Arrays

SystemVerilog dynamic arrays are a special class of array which can be resized whilst a simulation is running.

This differentiates them from static arrays which are allocated memory during compile time and have a fixed sized for the duration of a simulation.

This is useful as we may have instances where we don't know exactly how many elements our array will require when we compile our code.

The code snippet below shows how we declare a dynamic array in SystemVerilog.

When we create a dynamic array, we must always declare it as an unpacked type array .

As dynamic arrays are initially empty, we have to use the new keyword to allocate memory to the array before we can use it. We also declare the number of elements in the array when we use the new keyword.

The code example below shows how we would declare a dynamic array and then allocate the memory for 4 elements.

Dynamic Array Methods

Dynamic arrays are slightly more complex to work with than static arrays as we have to manage the size of the array in our code.

As a result of this, a number of methods are included in the SystemVerilog to help us manage dynamic arrays.

We have already seen one of the most important of these methods in the previous section - the new method.

In addition to this, we also commonly use the delete and size methods to manage our dynamic arrays.

Let's take a closer a look at each of these methods in more detail.

  • The new Method

As we have previously seen, we use the new method to allocate memory to our dynamic array.

The code snippet below shows the general syntax we use to call the new method.

The <size> field in this construct is used to specify how many elements there will be in the array.

We use the <values> field to assign values to the array after it has allocated memory. We can exclude this field if we are creating an empty array.

For example, we would use the code shown below to allocate memory for 8 elements in a dynamic array.

We can call the new method as many times as necessary in our code. Each time we call the new method, we effectively create a new array and allocate memory to it.

For example, we might need to replace our array of 8 elements with a new array which has 16 elements. In this case, we would simply call the new method a second time to resize our array.

The code snippet below shows how we would use the new method to do this.

When we use the new method in this way, any contents which were in the old array are deleted. This means that we create an entirely new, empty array when using this method.

However, we can also keep the existing contents of our array when we call the new method.

To do this, we need to pass the existing array to the new method using the <value> field we mentioned before. This will place the contents of the old array at the start of the resized array.

For example, suppose that we had created a dynamic array which consists of 8 elements and assigned some data to it.

If we now wanted to resize the array to 16 elements and keep the existing data, we could do this using the code shown below. This code can also be simulated on eda playground .

  • The delete Method

We use the delete method to remove the entire contents of a dynamic array.

When we call this method, it not only deletes the contents of the dynamic array but also deallocate the memory. In this sense, we can consider the delete method to be roughly equivalent to the free function in C .

The code snippet below shows the general syntax of the delete method.

In this construct, the <name> field is used to identify the dynamic array which we are calling the method on.

The SystemVerilog code below shows how we would use the delete method in practise. This code can also be simulated on eda playground .

  • The size Method

We use the size method to determine how large our dynamic array is at any given time.

When we call this method it returns a value which is equal to the number of elements in an array.

As we can see from this, it performs a similar function to the $size macro which we mentioned in the post on static arrays.

The code snippet below shows the general syntax for this method.

The SystemVerilog code below shows how we would use the size method in practise. This code can also be simulated on eda playground .

SystemVerilog Queues

SystemVerilog queues are a type of array which are automatically resized when we add or remove elements to the array.

The code snippet below shows how we would declare a queue type in SystemVerilog.

In this construct, we use the $ symbol inside of square brackets to indicate that we are creating a queue type.

We use the optional <max_length> field to limit the amount of elements which a queue can have.

However, we often exclude the <max_length> field from our declaration. When we do this, our queue can contain an unlimited amount of elements.

Queues which have an unlimited amount of elements are known as unbounded arrays whilst queues which are declared using the <max_length> field are known as bounded arrays.

When we declare a queue we can initialize it using a comma separated list of values between a pair of curly braces. This is similar to the use of array literals which we discussed in the previous post.

The SystemVerilog code below shows how we declare both a bounded and an unbounded queue. We also initialize both of the example queues with 2 elements.

  • Dynamic Arrays vs Queues

Dynamic arrays and queues actually perform very similar functions in SystemVerilog as they are both allocated memory at run time. As a result of this, we can resize both of these data structures whilst our code is running.

However, we use them for different purposes as they are optimized for slightly different operations.

We use queues when we are only interested in adding or removing elements at the beginning or end of the array.

The reason for this is that dynamic arrays are stored in contiguous memory addresses during simulation. As a result of this, when we resize a dynamic array it is often necessary for the entire array to be moved to a new location in memory.

In contrast, SystemVerilog queues are implemented in a similar way to linked lists in other programming languages.

This means that it is much quicker to add or remove elements to a queue as there is no need to move the existing elements in the array.

We typically use SystemVerilog queues to emulate either FIFO or LIFO type memories. We often see queues used in this way to move transactions between different blocks in a SystemVerilog based testbench.

However, when we want to access elements in the middle of the data structure then dynamic arrays are more efficient

The reason for this is that our simulator must start from either the beginning or end of the queue and loop through the memory until it reaches the required element. Again, this behavior is similar to linked lists in other programming languages.

In contrast, our simulator can directly access any element in dynamic array.

As we can see from this, it is clearly much quicker for our simulator to retrieve data from the middle of a dynamic array as less memory accesses are required.

Queue Methods

SystemVerilog queues are more complex that static arrays due to the fact that they require dynamic memory allocation .

As a result of this, we have a number of in built methods which can use to manipulate the contents of our queue.

This is in contrast to arrays where we can directly access individual elements to manipulate the contents of the array.

Let's take a closer a look at the most important queue methods in SystemVerilog.

  • Push to Queue

When we want to add data to a SystemVerilog queue, we can use either the push_front or the push_back method.

The push_front method inserts the specified data onto the front of the queue whilst the push_back method inserts the data at the end fo the queue.

We can think of the front of the queue as being equivalent to the lowest indexed element of a normal array.

In contrast, when we talk about the back of a queue this is equivalent to the highest indexed element of a normal array type.

The picture below illustrates the concept of push_front and push_back queue methods.

The code snippet below shows the general syntax we use to call the push_front and push_back methods.

In this construct we use the <queue_name> field to identify the queue we are adding data to.

We then use the <value> field to specify the value of the data which we are adding to the queue. We can use either a hard coded value or a variable to add data to our queue.

The SystemVerilog code below shows how we use the push_front and push_back methods in practise. This code can also be simulated on eda playground .

  • Pop From Queue

When we want to get some data from a SystemVerilog queue we use either the pop_front or pop_back methods.

The pop_front method retrieves data from the front of the queue whilst the pop_back method retrieves the data at the end fo the queue.

As with push_front method, the front of the queue is equivalent to the lowest indexed element of a normal array.

In constrast, the back of a queue is equivalent to the highest indexed element of a normal array type.

When we call either of these methods, the required element is removed from the queue and the value of this element is returned by the function.

The picture below illustrates the concept of pop_front and pop_back queue methods.

The code snippet below shows the general syntax we use to call the pop_front and pop_back methods.

In this construct we use the <queue_name> field to identify the queue we are retrieving data from.

The SystemVerilog code below shows how we use the pop_front and pop_back methods in practise. We can also simulate this code on eda playground .

  • Insert and Delete Methods

We can also use the insert and delete methods to add or remove an element in a SystemVerilog queue.

In contrast to the push and pop methods, we use these two methods to add or remove elements at a specific location in the queue.

As a result, we can use these methods to modify elements in the middle of our array.

However, we should be aware that these methods are less efficient than the push and pop methods. In addition, they can also be inefficient in comparison to the equivalent methods in dynamic arrays.

In fact, when we make extensive use of the insert or delete methods this may be a good indication that we should be using a dynamic array instead.

The code snippet below shows the general syntax we use to call the insert and delete methods.

In this construct we use the <queue_name> field to identify the queue which we are modifying.

We use the <value> field to specify the value of the data which we are adding to the queue. We can use either a hard coded value or a variable to add data to our queue.

In the case of the insert method, we use the <index> field to specify where the new element will be inserted in our queue.

In the case of the delete method, we use the <index> field to specify which element of the queue will be removed.

However, we can omit the <index> field when we use the delete method. When we do this, the entire content of our queue will be deleted.

The SystemVerilog code below shows how we use the insert and delete methods in practise. This code can also be simulated on eda playground.

SystemVerilog Associative Arrays

The final type of array which we can use in SystemVerilog is the associative array.

When we declare an associative array, memory for the array is not allocated at compile time and we can resize the array during simulation.

Therefore, associative arrays are very similar to the dynamic arrays which we discussed previously in this post.

However, the way that we index associative arrays is different from the way that we index dynamic arrays.

As we previously saw, we use sequential integers to index different elements of a dynamic array.

In contrast, we can use any value that we want to index the different elements of an associative array in SystemVerilog.

For example, we could use non sequential integers if we wanted to model the contents of a sparsely populated memory.

However, we could also use a string to give a physical name to the indexes in an associative array.

As we can see from this, we can think of associative arrays as being roughly equivalent to key-value pairs in other programming languages.

The SystemVerilog below shows the general syntax we use to declare an associative array.

When we use associative arrays, we must use the same data type for all of the indexes. This means that we can't mix int types and strings, for example.

We use the <key_type> field to declare what data type we will use for the index.

When we use associative arrays in our SystemVerilog code, the simulator has to search for the memory location of each element in the array when we either read or write to it.

As a result of this, associative arrays are less efficient than both static and dynamic arrays. This normally results in slowly execution times for our test benches.

Therefore, we generally prefer to use either a static or dynamic array instead of associative arrays whenever it is possible.

  • Assigning Data to an Associative Array

We can assign values to an associative array using the same techniques which we discussed in the previous post.

However, when we use array literals to we have to specify not only the data which we are assigning but also the value of the index we want associated with that data.

The SystemVerilog code below shows the general syntax we use to assign data to an associative array using array literals.

In this construct, we use the <key> field to set the value of the index in the array. The <data> field is then used to set the value of the data which is written to the array.

We can also use square brackets to access elements in an associative array. The syntax for this is exactly the same as we use for both static and dynamic arrays.

The SystemVerilog code below shows how we use associative arrays in practise. This code can also be simulated on eda playground .

What is the difference between static arrays and dynamic arrays in SystemVerilog?

Static arrays have a fixed number of elements which are determined at compile time. In contrast, dynamic arrays don't have a fixed sized and we can add or remove elements during simulation.

Write the code to declare a dynamic array of int types and allocate the memory for 8 elements

Which method would we use to deallocate the memory of a dynamic array?

We use the delete method to discard the contents of a dynamic array and dellocate any memory associated with it.

Write some code which creates a queue of int types and initializes 3 elements to 0.

When would we use queues instead of dynamic arrays in SystemVerilog? Why would we use queues in this circumstance.

We use queues when we only want to add or remove data from the beginning or end of the array. The reason for this is that it is more efficient to resize queues than it is to resize dynamic arrays. However, it is more efficient to access elements in the middle of a dynamic array.

Write some code which declares an associative array of int types and uses string type indexes.

2 comments on “SystemVerilog Dynamic Arrays and Queues”

nice post !please keep up good work ! Thank you.

In the " insert and delete"section about

// Create a queue with some initial values in it int example_q [$] = { 1, 2 }; // Insert a value into the

the code example is no complete ?

Hi Kaia, Thanks for pointing that out, I have updated the post so that the example is compete now.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Table of Contents

Sign up free for exclusive content.

Don't Miss Out

We are about to launch exclusive video content. Sign up to hear about it first.

Associative array in SystemVerilog

Associative array declaration, associative array methods.

function int size();

Returns the size of an associative array. Returns 0 if an array is empty

function int num();

Returns the number of entries of an associative array.

function int exists (input index)

Returns 1 if an element exists at a specified index else returns 0.

function int first (value)

Assign a value of the first index to the ‘value’ variable else returns 0 or an empty array.

function int last (value)

Assign a value of the last index to the ‘value’ variable else returns 0 or an empty array.

function int prev (value)

Assign a value of the previous index to the ‘value’ variable.

function int next (value)

Assign a value of the next index to the ‘value’ variable.

function void delete (input index)

Delete array entry for mentioned array index.

function void delete ()

Delete complete array means all entries will be removed.

Why do we need an associative array in SystemVerilog?

Associative array example, associative array methods example.

Verification Guide

  • Fixed Size Arrays
  • Packed and Un-Packed Arrays
  • Dynamic Array
  • Associative Array

❮ Previous Next ❯

SystemVerilog Unpacked Arrays

An unpacked array is used to refer to dimensions declared after the variable name.

Unpacked arrays may be fixed-size arrays, dynamic arrays , associative arrays or queues .

Single Dimensional Unpacked Array

Multidimensional unpacked array, packed + unpacked array.

The example shown below illustrates a multidimensional packed + unpacked array.

In a multidimensional declaration, the dimensions declared before the name vary more faster than the dimensions following the name.

DMCA.com Protection Status

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Verilog Array Assignment

So I am trying to assign numbers to an array in verilog, and it goes like this:

And the following codes can pass ModelSim Compiler. However, I have a huge lookup table need to store in this "waveforms", so apparently assign the value one by one is not efficient. So I tried this:

And, by doing the above, I get the following error:

So, question is how to fix these errors?

Tony's user avatar

Only SystemVerilog allows you to assign arrays as an aggregate. Change the file extension from *.v to *.sv

Another option is to use $readmemb and load the lookup table from another file.

dave_59's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged arrays verilog fpga modelsim or ask your own question .

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • How to handle stealth before combat starts?
  • Convert a Dataset into a list of lists and back to a Dataset
  • How would a culture living in an extremely vertical environment deal with dead bodies?
  • Erase the loops
  • How to cite a book if only its chapters have DOIs?
  • Cumulative Addition of Index Switch Node Values
  • Rendering React SPAs within Salesforce
  • Should I pay off my mortgage if the cash is available?
  • Why would Space Colonies even want to secede?
  • With 42 supernovae in 37 galaxies, how do we know SH0ES results is robust?
  • Is there any point "clean-installing" on a brand-new MacBook?
  • Stargate "instructional" videos
  • Word to classify what powers a god is associated with?
  • Dual UK/CAN national travelling from UK to Canada and back - which passport should I use to book tickets?
  • Guitar amplifier placement for live band
  • How to create a extruded 4-star shape that is rotated inwards?
  • Repeats: Simpler at the cost of more redundant?
  • Next Bitcoin Core client version
  • What is the purpose of toroidal magnetic field in tokamak fusion device?
  • I submitted a paper and later realised one reference was missing, although I had written the authors in the body text. What could happen?
  • Wiring 2 generators and utilizing a subpanel
  • Are there jurisdictions where an uninvolved party can appeal a court decision?
  • How do you "stealth" a relativistic superweapon?
  • What is the airspeed record for a helicopter flying backwards?

array assignment in system verilog

IMAGES

  1. Verilog Array

    array assignment in system verilog

  2. SystemVerilog Multidimensional Arrays

    array assignment in system verilog

  3. Systemverilog Dynamic Array

    array assignment in system verilog

  4. Verilog Continuous Assignment

    array assignment in system verilog

  5. System Verilog Data types and Arrays

    array assignment in system verilog

  6. SystemVerilog 2d array

    array assignment in system verilog

COMMENTS

  1. An Introduction to SystemVerilog Arrays

    An Introduction to SystemVerilog Arrays. This post of the the first of two which talk about SystemVerilog arrays. In this post, we will talk about static arrays, array assignment, loops and packed vs unpacked arrays. In SystemVerilog, we can write arrays which have either a fixed number of elements or a variable number of elements.

  2. SystemVerilog Arrays

    In the example shown below, a static array of 8-bit wide is declared, assigned some value and iterated over to print its value. bit [7:0] m_data; // A vector or 1D packed array. initial begin. // 1. Assign a value to the vector. m_data = 8'hA2; // 2. Iterate through each bit of the vector and print value.

  3. SystemVerilog Arrays

    An array is a group of variables having the same data type. It can be accessed using an index value. An index is a memory address and the array value is stored at that address.

  4. SystemVerilog Array Manipulation

    There are many built-in methods in SystemVerilog to help in array searching and ordering. Array manipulation methods simply iterate through the array elements and each element is used to evaluate the expression specified by the with clause. The iterator argument specifies a local variable that can be used within the with expression to refer to the current element in the iteration.

  5. SystemVerilog Associative Array

    SystemVerilog Associative Array. When size of a collection is unknown or the data space is sparse, an associative array is a better option. Associative arrays do not have any storage allocated until it is used, and the index expression is not restricted to integral expressions, but can be of any type. An associative array implements a look-up ...

  6. Mastering SystemVerilog Arrays: A Comprehensive Guide

    Welcome to "Mastering SystemVerilog Arrays: A Comprehensive Guide.". In the realm of hardware design and verification, SystemVerilog stands out as a powerful language, and understanding its array of capabilities is crucial for harnessing its full potential. Arrays in SystemVerilog offer a versatile and efficient way to manage data, making ...

  7. SystemVerilog Arrays, Flexible and Synthesizable

    SystemVerilog Arrays, Flexible and Synthesizable. October 10, 2017 by Jason Yu. In my last article on plain old Verilog Arrays, I discussed their very limited feature set. In comparison, SystemVerilog arrays have greatly expanded capabilities both for writing synthesizable RTL, and for writing non-synthesizable test benches.

  8. SystemVerilog Multidimensional Arrays

    "SystemVerilog arrays" is a big topic and I had to leave out many ideas. There were several questions on Multidimensional Arrays (MDAs), so here is a very short introduction. Copy and paste this code and run on your favorite simulator. Get dirty, make mistakes, debug - you are a verification engineer so figure it out! ... You can assign ...

  9. Verilog Arrays Plain and Simple

    The accompany source code for this article is a toy example module and testbench that illustrates SystemVerilog array capabilities, including using an array as a port, assigning multi-dimensional arrays, and assigning slices of arrays. Download and run it to see how it works! [lab_subscriber_download_form download_id=11].

  10. Easy way to assign values to an array in Verilog?

    But when you have 256 values to assign this is a very long process manually organising the code, even with Find/Replace you can only do so much. What I want is the ability to assign values to arrays like you can in System Verilog: reg [15:0] datafile [8] = '{8468,56472,56874,358,2564,8498,4513,9821};

  11. Verilog Arrays and Memories

    An array can be formed for any of the different data-types supported in Verilog. Note that a memory of n 1-bit reg is not the same as an n-bit vector reg. Array Assignment. y1 = 0; // Illegal - All elements can't be assigned in a single go. y2[0] = 8'ha2; // Assign 0xa2 to index=0.

  12. SystemVerilog Dynamic Arrays and Queues

    The SystemVerilog code below shows the general syntax we use to assign data to an associative array using array literals. // General syntax for array literals. <array_name> = '{ <key> : <data>, <key> : <data> }; In this construct, we use the <key> field to set the value of the index in the array.

  13. Associative array in SystemVerilog

    Returns 0 if an array is empty. Returns the number of entries of an associative array. Returns 1 if an element exists at a specified index else returns 0. Assign a value of the first index to the 'value' variable else returns 0 or an empty array. Assign a value of the last index to the 'value' variable else returns 0 or an empty array.

  14. SystemVerilog Dynamic Array

    SystemVerilog Dynamic Array. A dynamic array is an unpacked array whose size can be set or changed at run time, and hence is quite different from a static array where the size is pre-determined during declaration of the array. The default size of a dynamic array is zero until it is set by the new() constructor.

  15. SystemVerilog 2d array

    SystemVerilog 2d array initialization The two-dimensional array is an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. SystemVerilog 2D array Syntax data_type array_name [rows][columns]; SystemVerilog 2D array declaration int array [2:0][3:0]; The data in a two-dimensional array is stored in a tabular … Continue reading ...

  16. SystemVerilog Arrays

    SystemVerilog Arrays tutorila arrays examples Fixed Size Arrays Packed and Un-Packed Arrays Dynamic Array Associative Array Queues

  17. SystemVerilog Unpacked Arrays

    In a multidimensional declaration, the dimensions declared before the name vary more faster than the dimensions following the name. An unpacked array is used to refer to dimensions declared after the variable name. Unpacked arrays may be fixed-size arrays, dynamic arrays, associative arrays or queues.

  18. How to define and assign Verilog 2d Arrays

    13. First of all, you can't assign to regs. assigns drive wire types, not reg types. To drive a reg type you need a statement inside a logic block like an always block. Secondly, based on what you've written, I think you're looking for an array of multi-bit elements, not a 2d array. reg arr[5:0][0:5]; Defines a 2D array of single bits.

  19. Verilog Array Assignment

    So I am trying to assign numbers to an array in verilog, and it goes like this: initial begin. waveforms[0] = 16'b1100100100000000; waveforms[1] = 16'b1000000000000000; waveforms[2] = 16'b1111111111111111; end. And the following codes can pass ModelSim Compiler. However, I have a huge lookup table need to store in this "waveforms", so ...