导读 条件(if)语句用于控制执行语句要根据条件判断来确定是否执行。条件语句用关键字 if 和 else 来声明,条件表达式必须在圆括号中。
关键词:if,选择器
条件语句

条件(if)语句用于控制执行语句要根据条件判断来确定是否执行。

条件语句用关键字 if 和 else 来声明,条件表达式必须在圆括号中。

条件语句使用结构说明如下:

if (condition1)       true_statement1 ;
else if (condition2)        true_statement2 ;
else if (condition3)        true_statement3 ;
else                      default_statement ;
  1. if 语句执行时,如果 condition1 为真,则执行 true_statement1 ;如果 condition1 为假,condition2 为真,则执行 true_statement2;依次类推。
  2. else if 与 else 结构可以省略,即可以只有一个 if 条件判断和一组执行语句 ture_statement1 就可以构成一个执行过程。
  3. else if 可以叠加多个,不仅限于 1 或 2 个。
  4. ture_statement1 等执行语句可以是一条语句,也可以是多条。如果是多条执行语句,则需要用 begin 与 end 关键字进行说明。

下面代码实现了一个 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

仿真结果如下。

由图可知,输出信号与选择信号、输入信号的状态是相匹配的。

事例中 if 条件每次执行的语句只有一条,没有使用 begin 与 end 关键字。但如果是 if-if-else 的形式,即便执行语句只有一条,不使用 begin 与 end 关键字也会引起歧义。

例如下面代码,虽然格式上加以区分,但是 else 对应哪一个 if 条件,是有歧义的。

实例

if(en)
    if(sel == 2'b1)
        sout = p1s ;
    else
        sout = p0 ;

当然,编译器一般按照就近原则,使 else 与最近的一个 if(例子中第二个 if)相对应。

但显然这样的写法是不规范且不安全的。

所以条件语句中加入 begin 与 and 关键字就是一个很好的习惯。

例如上述代码稍作修改,就不会再有书写上的歧义。

实例

if(en) begin
    if(sel == 2'b1) begin
        sout = p1s ;
    end
    else begin
        sout = p0 ;
    end
end

原文来自:https://www.runoob.com/w3cnote/verilog-condition-statement.html

本文地址:https://www.linuxprobe.com/verilog-conditional-statements.html编辑:王艳敏,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/