Is a bad practice to use long nested if-else in assign statement?

岁酱吖の 提交于 2019-12-10 22:44:51

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/23091314/is-a-bad-practice-to-use-long-nested-if-else-in-assign-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!