title: Testbench of a Mux 4x1 using Verilog
body: <p>I am trying to use a testbench to test some features of a 4X1 Mux [a,b,c,d are the inputs , z is the output and s is the select line]. Here is my code: </p>
  
  <pre><code>module testbench_MUX();
  
  
  
    reg a,b,c,d;
  
    reg [1:0] s;
  
    wire z ; 
  
  
    MUX4_1 mux(.a(a) ,.b(b),.c(c),.d(d), .s(s),.z(z));
  
  
    initial begin 
      $dumpfile("dump.vcd");
      $dumpvars;
    end 
  
  initial begin // {
       a='b0;b='b1 ;c='b0 ;d='b1 ;s='d0;#15
      if(z==0) $display("time : %0t Test # 1 : passed",$time);
      a='b0;b='b1 ;c='b0 ;d='b1 ;s='d1;#15
      if(z==1) $display("Test # 2 : passed");
      a='b0;b='b0 ;c='b1 ;d='b1 ;s='d1; #15
      if(z==0) $display("Test # 3 : passed");
      a='b1;b='b0 ;c='b0 ;d='b0 ;s='d1; #15
      if(z==0) $display("Test # 4 : passed");
  
      $finish;
      end // } 
  </code></pre>
  
  <p>Here is the waveform:</p>
  
  <p><a href="https://i.stack.imgur.com/jinvk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jinvk.jpg" alt="enter image description here"></a></p>
  
  <p>The kernel displays that test 1 has passed, meaning that z=0:</p>
  
  <pre><code># KERNEL: time : 15Test # 1 : passed
  </code></pre>
  
  <p>But, as you can see from the waveform at time 15ns (the simulation timescale is 1ns/1ns), z=1.  Why does the <code>if</code> statement execute?</p>
  
  <p>MUX designcode : </p>
  
  <pre><code>module MUX4_1(
    input  a,b,c,d, 
    input   [1:0] s,
    output reg  z
  
  );
    always @ (*) begin
      if ( s==0) 
        z=a;
  
      else if ( s==1) 
        z=b;
  
      else if ( s==2) 
        z=c;
      else if (s==3)
  
        z=d;
  
      else  
        z=a;
  
    end 
  
  endmodule: MUX4_1
  </code></pre>