Branch Statements

The if statement.

Syntax: if (conditional_expression) statement{ else statement}

The if statement causes a conditional branch. If the conditional expression evaluates to true the first statement or set of statements is executed, else the second statement or set of statements is executed, ( the syntax is very similar to that of pascal). To group statements use the keywords begin... end

To illustrate the use of an if statement consider the 4 to 1 multiplexor in figure A, implemented using a logic equation in example B and using an if statement in example C.

Figure A : Above : The 4 to 1 multiplexor


        module multiplexor4_1 (out, in1, in2, in3 ,in4, cntrl1, cntrl2);
           output out;
           input in1, in2, in3, in4, cntrl1, cntrl2;

           assign out = (~cntrl2 & ~cntrl1 & in1) | // The output is in1 when both
                        ( cntrl2 & ~cntrl1 & in2) | // cntrls are low, etc.
                        (~cntrl2 &  cntrl1 & in3) |
                        ( cntrl2 &  cntrl1 & in4) ;
           // Note this is a continous assignment, if an operand on the right
           // hand side changes, the left hand side will reflect the change.

        endmodule


Example B : Above : Implementation of a 4 to 1 multiplexor using a logic equation.

        module  multiplexor4_1 (out, in1, in2, in3 ,in4, cntrl1, cntrl2);
           output out;
           input in1, in2, in3, in4, cntrl1, cntrl2;
           reg out; // Note that this is now a register

           always @(in1 or in2 or in3 or in4 or cntrl1 or cntrl2)
              if (cntrl1==1)
                 if (cntrl2==1)
                    out = in4;
                 else out = in3;
              else
                 if (cntrl2==1)
                    out = in2;
                 else out = in1;

        endmodule

Example C : Above : Implementation of a 4 to 1 multiplexor using a if statement.

EXERCISE
Write the stimulus block for the above multiplexor, you will have to show that the correct input is selected according to the values of the control bits.

Answers


next contents