Home > Enterprise >  If else condition precedence in Verilog
If else condition precedence in Verilog

Time:01-04

I have noticed that there is a precedence of assignment while using if-else conditionals in Verilog. For example as in the code below:

if(counter < 6)
  z <= 1;
else if(counter < 12)
  z <= 2;
else
  z <= 3;

I noticed that until the counter is less than 6, the value of z is assigned the value of 1 (z <= 1) and as soon as the value of the counter exceeds 6 and is less than 12, z is assigned the value 2 (z <= 2).

What if there are different variables used inside the conditionals as in the code below?

if(wire1_is_enabled)
  z <= 1;
else if(wire2_is_enabled)
  z <= 0;

What happens when both conditions are true? What is the behaviour of the assignment operator here? I believe this is poor programming habit.

CodePudding user response:

The 2 if/else statements behave the same way; the first condition to be true has the highest priority. Once a condition evaluates to true, all the following else clauses are ignored. Therefore, z <= 1 if both wire1_is_enabled and wire2_is_enabled are true. This is easy to prove to yourself with a simple simulation.

This is not a poor coding habit. This situation is common in Verilog. When you say programming, perhaps you are thinking of software languages. Keep in mind that these are hardware signals instead of software variables.

CodePudding user response:

Yes, nested if-else branching statements naturally assume a priority in the order of execution. Think about using a case statement instead of deeply nesting if statements which are much more readable.

There is nothing wrong with this coding style unless you have code like:

if(counter < 6)
  z <= 1;
else if(counter < 2)
  z <= 2; // unreachable
else
  z <= 3;

Then the statement z <= 2; becomes unreachable because when the first condition is false, the second condition can never be true. Fortunately there are a number of tools that can flag this problem for you.

Both if and case statements assume priority logic. However, you have an option to explicitly add a priority or unique keyword before the if or case keywords to declare and check your intent. See sections 12.4 and 12.5 in the IEEE 1800-2017 SystemVerilog LRM.

CodePudding user response:

else if statements is the catch after the if statement was false.

The control flow never reaches the else if statements if the if was true. So if you want to execute both statements, you should using two separate if statements like this:

if (wire1_is_enabled)
  z <= 1;
if (wire2_is_enabled)
  z <= 0;
  •  Tags:  
  • Related