• 1

    ..

  • 2

    ...

  • 3

    ...

Thursday 2 November 2017

conditional operator (?:) vs IF statement

Here is the simple code for comparing conditional operator and if statement.

Code:
module testing;
  reg foo;
  wire [3:0] c1,c2,c3;
  reg [3:0] a=1,b=3,cif1,cif2,cif3;
  
  assign c1 = foo ? a : b;  

  //equality
  assign c2 = (foo==1) ? a : b;

  //case equality
  assign c3 = (foo===1) ? a : b;
  
  always@(foo or a or b) begin 
    if (foo) 
      cif1 = a;
    else 
      cif1 = b;

    //equality
    if (foo==1) 
      cif2 = a;
    else 
      cif2 = b;
    //case equality
    if (foo===1) 
      cif3 = a;
    else 
      cif3 = b;
  end
  
  initial begin
    $monitor("@%3t :: foo=%b, a=%x, b=%x,   c1=%x, c2=%x, c3=%x,   cif1=%x ,cif2=%x ,cif3=%x", $realtime,foo,a,b,c1,c2,c3,cif1,cif2,cif3);
    #10 foo=1;
      #5 a=a+1;
    #10 foo=0;
      #5 b=b+1;
    #10 foo=1;
  end
  
endmodule

OUTPUT:
@  0 :: foo=x, a=1, b=3,   c1=X, c2=X, c3=3,   cif1=3 ,cif2=3 ,cif3=3  @ 10 :: foo=1, a=1, b=3,   c1=1, c2=1, c3=1,   cif1=1 ,cif2=1 ,cif3=1  @ 15 :: foo=1, a=2, b=3,   c1=2, c2=2, c3=2,   cif1=2 ,cif2=2 ,cif3=2  @ 25 :: foo=0, a=2, b=3,   c1=3, c2=3, c3=3,   cif1=3 ,cif2=3 ,cif3=3  @ 30 :: foo=0, a=2, b=4,   c1=4, c2=4, c3=4,   cif1=4 ,cif2=4 ,cif3=4  @ 40 :: foo=1, a=2, b=4,   c1=2, c2=2, c3=2,   cif1=2 ,cif2=2 ,cif3=2  

Based on the simulation, when the condition is X conditional operator outputs X whereas if statement outputs else part. Except this, moreover no difference in execution of these two.

Search Here...