常量数组
初始化数组:
int ascend[4] = '{0,1,2,3};
int descend[5];
descend = '{4,3,2,1,0};
descend = '{9,8,default:1};//为未显示赋值的元素指定一个缺省值
foreach循环中,只需要指定数组名并在其后方括号中给出索引变量,SV便会自动遍历数组中的元素,索引变量将自动声明,并只在循环内有效
//在数组中使用for和foreach
initial begin
bit[31:0] src[5],dst[5];
for(int i=0;i<$size(src);i++)
src[i] = i;
foreach(dst[j])
dst[j] = src[j] * 2;
end
//在多维数组中使用for和foreach
int md[2][3] = '{'{0,1,2},'{3,4,5}};
initial begin
foreach(md[i,j])//注意,不同于C语言,不是md[i][j]
$display("md[0%d][0%d]=%0d",i,j,md[i][j]);
end
//如果不需要遍历数组中所有维度,可以在foreach中忽略掉某些维度
initial begin
byte twoD[4][6];
foreach(twoD[i,j])
twoD[i][j]=i*10+j;
foreach(twoD[i])begin
$write("%2d:",i);
foreach(twoD[,j])
$write("%3d",twoD[i][j]);
$display;
end
end
//foreach循环会遍历原始声明中的数组范围 数组f[5]等同于f[0:4] foreach(f[i])等同于
//for(int i=0;i<=4;i++),对于数组rev[6:2]来说,foreach(rev[i])等价于for(int i=6;i>=2;i--)
//数组的复制和比较操作
initial begin
bit[31:0] src[5] = '{0,1,2,3,4},
dst[5] = '{5,4,3,2,1};
//两个数组的聚合比较
if(src == dst)
$display("dst == src");
else
$display("dst != src");
dst = src;
src[0] = 5;
$display("src %s dst",(src == dst) ?"==":"!=");
//使用数组片段对第1-4个元素进行比较
$display("src[1:4] %s dst[1:4]",
(src[1:4] == dst[1:4])?"==":"!=");
end
//对数组的算术运算不能使用聚合操作,要使用循环,如加法,对逻辑运算如异或只能使用循环或合并数组
//同时使用位下标和数组下标
initial begin
bit[31:0] src[5] = '{5{5}};
$displayb(src[0],//'b101 或'd5
src[0][0],//'b1 即'b101的第0位
src[0][2:1]);//'b10 即'b101的倒数高两位10
合并数组 既可以用作数组 也可以当成单独的数据,它的存放方式是连续的比特集合,中间没有闲置的空间
声明合并数组时 合并的位和数组大小作为数据类型的一部分必须在变量名前面指定,数组大小定义的格式必须是[msb:lsb],而不是
浙公网安备 33010602011771号