Search code examples
if-statementverilogsystem-veriloghdl

Two if statements in parallel assigning value to same variable in Verilog, what is the precedence then?


Let's say we have these two if conditions assigning values to the same variable and both if statements can be true at the same time. What value will x have? Lets say z and y are equal to 0.

From my testing in simulator, the if statement that was written lower in the code had precedence. The value of x was 1 when I simulated the code below with values of z and y equal to 0. When I had the if conditions swapped (the if condition with "!z" came at the end), then the value of x came out to be 0 in the simulation.

Is there a rule when such a condition happens in Verilog?

always @ (posedge clk) begin
  x <= 1'b0;

  if (!z) begin
    x <= 0;
  end

  if (!y) begin
    x <= 1;
  end 
end

Solution

  • The rules for all Verilog behavior are set in the IEEE Std 1800-2017. Section 9.3.1 Sequential blocks, states:

    A sequential block shall have the following characteristics:
      — Statements shall be executed in sequence, one after another.
    

    In this context, a sequential block is defined by the begin/end keywords.

    Also, section 10.4.2 Nonblocking procedural assignments:

    The order of the execution of distinct nonblocking assignments to a given variable shall be preserved.

    However, it is much more common to write your code so that each nonblocking assignment is unambiguous.

    always @ (posedge clk) begin
        if (!y) begin
            x <= 1;
        end else if (!z) begin
            x <= 0;
        end else begin
            x <= 0;
        end
    end
    

    When this code is simulated, only one of the 3 assignments will be executed.