Verilog If Else Structure

Verilog If Else Structure

a very simple question but want to know for parsing purpose :

Are these two structures same in verilog?

first code :

if_0                                        
else begin
          if_1
          else begin
                    if_2
                    end
          end
end

second code :

if 
    else if
        else if 
        end
    end
end

Or is there any instance you can think of where if else begin if and if else if might be different in any code structure?

3

2 Answers

The syntax of an if statement is

if (condition) true_statement; else false_statement;

Where the else false_statement; is optional. The use of begin/end is a distinct topic. Anywhere one procedural statement is allowed, you can replace it with a compound set of statements inside a begin/end block, and that includes wrapping one statement with begin/end. And if/else is considered a single statement. So you can have the following all mean the same thing

initial if (cond2) A=1; else if (cond2) B = 2; else C = 3;
initial begin if (cond1) A=1; else if (cond2) B = 2; else C = 3; end
initial if (cond1) A=1; else begin if (cond2) B = 2; else C = 3; end
initial if (cond1) A=1; else if (cond2) B = 2; else begin C = 3; end
initial begin if (cond1) begin A=1; end else begin if (cond2) begin B = 2 end ; else begin C = 3; end end end

Note that SystemVerilog adds labeling to begin : name and end : name to help match them up.

syntax of the if statement is

if (condition) begin
end

Taking the above in account, the following constructs are equivalent

if (condition1) begin
   ...
end
else begin
   if (condition2) begin
      ...
   end
   else begin
      ...
   end
end

and

 if (condition1) begin
     ...
 end
 else if (condition2) begin
     ...
 end
 else begin
     ...
 end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.