Verilog code for JK flip flop (gate level modelling) error in output (x propagation)

I have written Verilog code for a JK flip flop (gate level modelling), and I am getting an error in the output (error means x propagation). Why are my q and qb outputs x (the unknown Verilog value)? For example, when k=1 and j=0, I expect q=0.

module jk (q,qb,j,k,clk);
output q,qb;
input j,k,clk;
wire [1:0]a;
nand (a[0],j,clk,qb), (a[1],k,clk,q);
nand (q,a[0],qb), (qb,a[1],qb);
endmodule

module tb;
wire q,qb;
reg j,k,clk;
jk ff (.j(j), .k(k), .clk(clk), .q(q), .qb(qb));

initial begin
clk=0;
forever #5 clk=~clk;
end

initial begin
j=1'b0; k=1'b1;
#10 j=1'b1; k=1'b0;
#10 j=1'b1; k=1'b1;
#10 j=1'b0; k=1'b0;
#10 \$finish;
end
endmodule


Using a gate-level model for sequential logic like a flip-flop is the wrong tool for the job in Verilog. The right tool for the job is a behavioral model.

Your model with the nand instances has combinational feedback loops, which means you are always trying to set nodes in your circuit with different values at the same time. This results in unknowns (x). You could hack your model using delays or Verilog force statements to achieve what you want, but then your code would be hard to understand and maintain.

Here is a typical way to code a JK flip-flop:

module jk(q,qb,j,k,clk);
output q,qb;
input j,k,clk;
reg q;

always @(posedge clk) begin
case ({j, k})
2'b01: q <= 0;
2'b10: q <= 1;
2'b11: q <= ~q;
endcase
end

assign qb = ~q;
endmodule


This model is much easier to understand.

If you are experiencing an error in the output of the JK flip-flop, it is likely due to a problem with the input values or the implementation of the flip-flop itself.

One common issue that can cause X propagation errors is uninitialized variables. If any of the input variables (J, K, or clk) are uninitialized or have an unknown value, this can cause unpredictable behavior in the output. To fix this issue, you should make sure to initialize all variables before using them in the code.

Another possible cause of X propagation errors is a problem with the implementation of the flip-flop itself. Make sure that the code for the JK flip-flop is correct and that the logic gates are connected properly. Double-check the truth table for the JK flip-flop to ensure that it is implemented correctly.

If you have ruled out these issues, there may be a problem with the simulator or the Verilog compiler itself. In this case, you should try using a different simulator or compiler to see if the error persists.