You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用?:运算符出现结果不一致问题求助

Verilog中?:运算符与直接比较赋值的结果差异问题

在HDLBits的iverilog模拟器中,编写了如下测试代码,预期out1和out2的输出结果完全一致,但实际波形显示两者结果不同。

module top_module ();
reg clk=0;
always #5 clk = ~clk;  // Create clock with period=10
initial `probe_start;   // Start the timing diagram

`probe(clk);        // Probe signal "clk"

// A testbench
reg[1:0] in1=2'b10;
reg[1:0] in2 =2'b01;
initial begin
    #10 in1 <= 2'b0;
        in2 <= 2'b0;
    
    $display ("Hello world! The current time is (%0d ps)", $time);
    #50 $finish;            // Quit the simulation
end

invert inst1 ( .in1(in1),.in2(in2) );   // Sub-modules work too.

endmodule

module invert(input [1:0]in1, input [1:0]in2, output out1,output out2);
    assign out1 = (in1^in2 == 2'b0) ? 1'b1 : 1'b0;
    assign out2 = in1^in2 == 2'b0;

    `probe(in1);    // Sub-modules can also have `probe()
    `probe(in2);
    `probe(out1);
    `probe(out2);
endmodule

波形图

问题原因

核心问题是Verilog运算符优先级导致的逻辑解析错误:
相等比较运算符==的优先级高于按位异或运算符^,因此assign out2 = in1^in2 == 2'b0;会被编译器解析为:

assign out2 = in1 ^ (in2 == 2'b0);

这和out1的逻辑完全不同:

  • out1是先计算in1与in2的异或结果,再判断该结果是否等于0,最终输出对应逻辑值;
  • out2则是先判断in2是否等于0,再将这个1位的判断结果与2位的in1做异或,最后截断为1位输出,逻辑完全偏离预期。

解决方案

给in1^in2加上括号,明确运算顺序,让代码逻辑符合预期:

assign out2 = (in1^in2) == 2'b0;

修改后,out2的逻辑与out1完全一致,两者输出结果会相同。

内容的提问来源于stack exchange,提问作者shikyeeee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 11:40:51