If Else in Verilog

Branching with if and else in Verilog is straightforward. Here’s a basic example:

module if_else;
  reg [3:0] num;
  
  initial begin
    // Basic if-else example
    if (7 % 2 == 0)
      $display("7 is even");
    else
      $display("7 is odd");

    // You can have an if statement without an else
    if (8 % 4 == 0)
      $display("8 is divisible by 4");

    // Logical operators like && and || are often useful in conditions
    if ((8 % 2 == 0) || (7 % 2 == 0))
      $display("either 8 or 7 are even");

    // A statement can precede conditionals
    num = 9;
    if (num < 0)
      $display("%0d is negative", num);
    else if (num < 10)
      $display("%0d has 1 digit", num);
    else
      $display("%0d has multiple digits", num);
  end
endmodule

To run this Verilog code, you would typically use a Verilog simulator like Icarus Verilog or ModelSim. Here’s an example of how you might run it using Icarus Verilog:

$ iverilog -o if_else if_else.v
$ vvp if_else
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in Verilog, you don’t need parentheses around conditions, but semicolons are required at the end of each statement. The begin and end keywords are used to group multiple statements in a block.

In Verilog, there is no direct equivalent to the ternary operator (?:) as found in some other languages. You’ll need to use a full if-else statement for conditional operations.

It’s important to note that this Verilog code is synthesizable and can be used to describe actual hardware behavior. The $display statements are used for simulation purposes and would not be part of the synthesized hardware.