Question

I sometimes use long assign statement in verilog which has nested if-else loop.

Example

assign a = (b) ? '1 : ((c&d) ? '0 : ((f&h) ? '1 : '0));

Another way to do this is to use an always_comb logic block. However the above approach saves time and easy to code up quickly.

Was it helpful?

Solution

Formatting

There is nothing wrong with a nested conditional continuous assignment, but there are ways to make it more readable:

assign a = (b)    ? '1
         : (c&d)  ? '0
         : (f&h)  ? '1
                  : '0;

However, this is still an "if...else if...else if...else" structure, and a question you should ask yourself is what is this code meant to do and how it would 'read'. The above may be easier to read (while synthesizing same code) if it is code using an always and ""if...else if...else if...else" structure.

Here is an example of a clean use of the nested conditional continuous assignment:

assign a = (state == STATE1) ? '1
         : (state == STATE2) ? '0
         : (state == STATE3) ? '1 
           /* default */     : '0;

Readability

Do consider, that your shown form may save time in the original typing of the code, but there is much higher value in having your code readable. Be it yourself, or another designer, looking at the code a year or more later will appreciate a form that allows them to quickly grasp what the logic is doing.

Coding can be sped up without loss of readability by using an editor that supports auto-expanding snippets (or abbreviations). I use vim with abbreviations that really speed up all block structure entry, and alignment scripts that allow me to vertically align given character (like "=" or "(") or string in selection.

OTHER TIPS

The answer to this question is probably more of a personal opinion, but in general long nested conditional statements like this are considered to be bad programming style because they are hard to debug and hard to maintain: http://cse.psu.edu/~cg577/DOCUMENTS/codingstandards/verilog.html

Besides if-else in always_comb, you can also use a case statement:

casez ({b,c,d,f,h})
    5'b1????: '1
    5'b011??: '0
    5'b00011: '1
    default: '0
endcase

You can also qualify casez with priority, unique, and unique_0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top