1
\$\begingroup\$

What does the Verilog localparam X code below mean? From my understanding it is as follows:

if(y==4)      X = +64;
else if(Y==3) X = +32;
else if(Y==2) X = +16;
else if(Y==1) X = +8;
else if(Y==0) X = +4;
else          X = +2;

Is this correct? If so, another thing that doesn't make sense to me is the '+' after the '=' sign, e.g., (X = +2)? Is this something unique to localparam variables?

localparam  X = (Y==4) ? +64 :
                (Y==3) ? +32 :
                (Y==2) ? +16 :
                (Y==1) ? +8  :
                (Y==0) ? +4  :
                         +2  ;
\$\endgroup\$
3
  • \$\begingroup\$ Your understanding of the conditional operator is correct. The unary + can be omitted. It is not unique to localparam, it can be anywhere. \$\endgroup\$
    – Eugene Sh.
    Commented Jan 13, 2023 at 16:12
  • \$\begingroup\$ Is there any reason why designers would use the '+' ? \$\endgroup\$
    – user367640
    Commented Jan 13, 2023 at 16:14
  • \$\begingroup\$ Could be multiple reasons or no reason at all :) For example it could be a remnant of some longer code involving negative numbers as well, so the +s were added for visual consistency. \$\endgroup\$
    – Eugene Sh.
    Commented Jan 13, 2023 at 16:17

2 Answers 2

0
\$\begingroup\$

Yes, the localparam statement is logically equivalent to the if/else pseudocode you showed. The statement uses the conditional operator which has precedence like your if/else.

The + signs are unnecessary in the code. The code behaves the same as if they were not there. Perhaps someone copy-and-pasted more complicated code (with expressions like A+2) and forgot to simplify it. A simpler way to write it is:

localparam  X = (Y==4) ? 64 :
                (Y==3) ? 32 :
                (Y==2) ? 16 :
                (Y==1) ? 8  :
                (Y==0) ? 4  :
                         2  ;
\$\endgroup\$
0
\$\begingroup\$

The conditional operator ?: is an expression that behaves similar to an if/else conditional branching procedural statement as you observed. It can be used in places where is is not practical to use procedural statements. A parameter/localparam must be assigned using an expression. You could wrap the if/else in a constant function, but the conditional operator is a convenience. If you were making assignments to a variable, a procedural case statement would be much clearer.

The unary + operator has no purpose other than symmetry with the unary - operator. In can make the intent of the code more clear if you have a mix of positive and negative numbers.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.