If-else Statement

If-Else Statements

The if-else statement allows you to conditionally execute a section of code. It works by evaluating a condition: if the condition is true, the code within the if block is executed; if the condition is false and an else block is provided, the code within the else block is executed.

Example:

module MyModule;
    integer a = 10;
    integer b = 20;
    initial begin
        if (a > b) 
            $display("a is greater than b");
        else 
            $display("a is not greater than b");
    end
endmodule

In this example, the message "a is not greater than b" will be printed, because the condition a > b is false.

Nested If-Else Statements

Nested if-else statements are useful when you need to check for more conditions inside an if or else block.

Example:

module MyModule;
    integer a = 10;
    integer b = 20;
    integer c = 15;
    initial begin
        if (a > b) 
            $display("a is greater than b");
        else {
            if (a > c) 
                $display("a is greater than c");
            else 
                $display("a is not greater than b or c");
        }
    end
endmodule

In this example, the message "a is not greater than b or c" will be printed.

Else If Chains

else if chains are useful when you need to check multiple conditions sequentially. If a condition is met, the corresponding code block will be executed, and the rest of the conditions will be ignored.

Example:

module MyModule;
    integer a = 10;
    integer b = 20;
    initial begin
        if (a > b) 
            $display("a is greater than b");
        else if (a == b) 
            $display("a is equal to b");
        else 
            $display("a is less than b");
    end
endmodule

In this example, the message "a is less than b" will be printed.

Have a Question?

Feel free to ask your question in the comments below.

Please Login to ask a question.

Login Now