Title here
Summary here
Here we use range
to sum the numbers in a slice. Arrays work like this too.
module range_example;
initial begin
// Define the array
integer nums[0:2];
nums[0] = 2;
nums[1] = 3;
nums[2] = 4;
// Sum the array elements
integer sum;
integer i;
sum = 0;
for (i = 0; i <= 2; i = i + 1) begin
sum = sum + nums[i];
end
$display("sum: %d", sum);
end
endmodule
range
on arrays and slices provides both the index and value for each entry. Above we didn’t need the index, so we ignored it. Sometimes we actually want the indexes though.
module range_with_index_example;
initial begin
// Define the array
integer nums[0:2];
nums[0] = 2;
nums[1] = 3;
nums[2] = 4;
// Print the index where the value is 3
integer i;
for (i = 0; i <= 2; i = i + 1) begin
if (nums[i] == 3) begin
$display("index: %d", i);
end
end
end
endmodule
range
on map iterates over key/value pairs.
module range_map_example;
initial begin
// Define the associative array (map)
string kvs[string];
kvs["a"] = "apple";
kvs["b"] = "banana";
// Iterate over the map
string key;
foreach (kvs[key]) begin
$display("%s -> %s", key, kvs[key]);
end
end
endmodule
range
can also iterate over just the keys of a map.
module range_map_keys_example;
initial begin
// Define the associative array (map)
string kvs[string];
kvs["a"] = "apple";
kvs["b"] = "banana";
// Iterate over just the keys
string key;
foreach (kvs[key]) begin
$display("key: %s", key);
end
end
endmodule
range
on strings iterates over Unicode code points. The first value is the starting byte index of the rune
and the second the rune
itself.
module range_string_example;
initial begin
// Define the string
string word;
word = "go";
// Iterate over the string
integer i;
for (i = 0; i < $size(word); i = i + 1) begin
$display("%d %d", i, word[i*8+:8]);
end
end
endmodule
Now that we understand how to use range
with arrays, slices, maps, and strings, let’s explore more about the language.