Search code examples
verilog

Different results with the ? : operator


I got a problem with the ? : operator. out1 and out2 should be the same, but I got a different result.

I tested this in HDLBits simulator iverilog.

Here's the code, and the picture below is the corresponding wave.

    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

enter image description here


Solution

  • Please check verilog operator precedence. == is higher than bit-wise ^. So in your original code,

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

    is treated as

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

    In the first part of the waveform, in1=2 and in2=1, so the above assignment becomes 2'h2 ^ ( 2'h1 == 2'h0 ), which is 2'h2. out2 gets the bit 0 of the result, which is 0.

    In the second part of the waveform, in1=0 and in2=0, so the above assignment becomes 2'h0 ^ ( 2'h0 == 2'h0 ), which is 2'h1. out2 gets the bit 0 of the result, which is 1.

    If the intent was to compare the bit-wise XOR of in1 and in2 to 2'b00, then use extra parentheses for both out1 and out2: (in1^in2)