If else condition precedence in Verilog

I have noticed that there is a precedence of assignment while using if-else conditionals in Verilog. For example as in the code below: I noticed that until the counter is less than 6, the value of z is assigned the value of 1 (z

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.

1

2 Answers

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.

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.

0

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobmltZm59dnyOop1mnZyosm6vzqeboqyZpLtuvNGemp6claOwpnnIp2SvnaKeubCz

 Share!