Title

SystemVerilog -- 3.3 SystemVerilog for loop

SystemVerilog for loop

SystemVerilog中的循环多次重复一组给定的语句,直到不满足给定的表达式。与所有其他过程块一样,循环中需要多个语句被forfor begin end关键字括起来。

Syntax

For循环使用三步方法控制其语句的执行:

  1. 初始化影响循环运行次数的变量
  2. 在执行循环之前,请检查条件是否为真
  3. 修改器在每次迭代结束时执行,并跳转到步骤2
for ([initialization]; <condition>; [modifier])
  // Single statement

for ([initialization]; <condition>; [modifier]) begin
  // Multiple statements
end

Example #1 - Array Iteration

在此示例中,我们将遍历字符串数组并打印出其内容。数组array使用5个不同的水果名称进行初始化。

循环初始化声明一个名为i的局部变量,该变量表示数组中任何元素的索引。条件表达式检查i是否小于数组的大小。修饰符递增i的值,以便循环的每次迭代都对不同的索引进行操作。for

module tb;
  string array[5] = '{"apple", "orange", "pear", "blueberry", "lemon"};

  initial begin
    for (int i = 0; i < $size(array); i++)
      $display ("array[%0d] = %s", i, array[i]);
  end
endmodule

模拟日志

ncsim> run
array[0] = apple
array[1] = orange
array[2] = pear
array[3] = blueberry
array[4] = lemon
ncsim: *W,RNQUIE: Simulation is complete.

Example #2 - Multiple Initializations

在循环的第一部分可以进行多次初始化。在下面显示的代码中,变量ij在输入for循环后立即初始化。为了使示例更有趣,j指向的每个字符串的索引都替换为0。for

module tb;
  string array[5] =' {"apple", "orange", "pear", "blueberry", "lemon"};

  initial begin
    for (int i = 0, j = 2; i < $size(array); i++) begin
      array[i][j] = "0";
      $display ("array[%0d] = %s, %0dth index replaced by 0", i, array[i], j);
    end
  end
endmodule

模拟日志

ncsim> run
array[0] = ap0le, 2th index replaced by 0
array[1] = or0nge, 2th index replaced by 0
array[2] = pe0r, 2th index replaced by 0
array[3] = bl0eberry, 2th index replaced by 0
array[4] = le0on, 2th index replaced by 0
ncsim: *W,RNQUIE: Simulation is complete.

Example #2 - Adding multiple modifiers

在下面显示的代码中,j在循环的每次迭代后都会递减,同时递增ifor

module tb;
  string array[5] =' {"apple", "orange", "pear", "blueberry", "lemon"};

  initial begin
    for (int i = 0, j = array[i].len()-1; i < $size(array); i++, j--) begin
      array[i][j] = "0";
      $display ("array[%0d] = %s, %0dth index replaced by 0", i, array[i], j);
    end
  end
endmodule

模拟日志

ncsim> run
array[0] = appl0, 4th index replaced by 0
array[1] = ora0ge, 3th index replaced by 0
array[2] = pe0r, 2th index replaced by 0
array[3] = b0ueberry, 1th index replaced by 0
array[4] = 0emon, 0th index replaced by 0
ncsim: *W,RNQUIE: Simulation is complete.

posted on 2024-05-05 19:11  松—松  阅读(249)  评论(0编辑  收藏  举报

导航