條件(if)語句用于控制執(zhí)行語句要根據(jù)條件判斷來確定是否執(zhí)行。
條件語句用關(guān)鍵字 if 和 else 來聲明,條件表達式必須在圓括號中。
條件語句使用結(jié)構(gòu)說明如下:
if (condition1) true_statement1 ;
else if (condition2) true_statement2 ;
else if (condition3) true_statement3 ;
else default_statement ;
true_statement1
?;如果 condition1 為假,condition2 為真,則執(zhí)行 ?true_statement2
?;依次類推。
ture_statement1
?就可以構(gòu)成一個執(zhí)行過程。
ture_statement1
?等執(zhí)行語句可以是一條語句,也可以是多條。如果是多條執(zhí)行語句,則需要用 begin 與 end 關(guān)鍵字進行說明。下面代碼實現(xiàn)了一個 4 路選擇器的功能。
module mux4to1(
input [1:0] sel ,
input [1:0] p0 ,
input [1:0] p1 ,
input [1:0] p2 ,
input [1:0] p3 ,
output [1:0] sout);
reg [1:0] sout_t ;
always @(*) begin
if (sel == 2'b00)
sout_t = p0 ;
else if (sel == 2'b01)
sout_t = p1 ;
else if (sel == 2'b10)
sout_t = p2 ;
else
sout_t = p3 ;
end
assign sout = sout_t ;
endmodule
testbench 代碼如下:
`timescale 1ns/1ns
module test ;
reg [1:0] sel ;
wire [1:0] sout ;
initial begin
sel = 0 ;
#10 sel = 3 ;
#10 sel = 1 ;
#10 sel = 0 ;
#10 sel = 2 ;
end
mux4to1 u_mux4to1 (
.sel (sel),
.p0 (2'b00), //path0 are assigned to 0
.p1 (2'b01), //path1 are assigned to 1
.p2 (2'b10), //path2 are assigned to 2
.p3 (2'b11), //path3 are assigned to 3
.sout (sout));
//finish the simulation
always begin
#100;
if ($time >= 1000) $finish ;
end
endmodule
仿真結(jié)果如下。
由圖可知,輸出信號與選擇信號、輸入信號的狀態(tài)是相匹配的。
事例中 if 條件每次執(zhí)行的語句只有一條,沒有使用 begin 與 end 關(guān)鍵字。但如果是 if-if-else 的形式,即便執(zhí)行語句只有一條,不使用 begin 與 end 關(guān)鍵字也會引起歧義。
例如下面代碼,雖然格式上加以區(qū)分,但是 else 對應(yīng)哪一個 if 條件,是有歧義的。
if(en)
if(sel == 2'b1)
sout = p1s ;
else
sout = p0 ;
當(dāng)然,編譯器一般按照就近原則,使 else 與最近的一個 if(例子中第二個 if)相對應(yīng)。
但顯然這樣的寫法是不規(guī)范且不安全的。
所以條件語句中加入 begin 與 and 關(guān)鍵字就是一個很好的習(xí)慣。
例如上述代碼稍作修改,就不會再有書寫上的歧義。
if(en) begin
if(sel == 2'b1) begin
sout = p1s ;
end
else begin
sout = p0 ;
end
end
點擊這里下載源碼
更多建議: