Operator precedence and potential problems

The precedence of operators in Systemverilog can sometimes be counterintuitive. For reference, here’s the table of precedence (going from highest down to lowest):

Vtool Operator precedence and potential problems

Notice that the add and subtract operators have a higher precedence than the shift operators, so the result of “a << b + c” actually means “shift a left for b + c positions” instead of “shift a left for b positions and then add c”. In some way, shifting can be thought of as multiplying/dividing (integer division) by a power of 2, and that’s why it’s natural to assume that shifting will be done first. Here’s an example with a function that’s supposed to generate a 32-bit number with n LSB bits set to 1:

Operator precedence and potential problems
The output of the $display call is:
Vtool Operator precedence and potential problems
Instead of the expected:
Vtool Operator precedence and potential problems

Another case involves equality and logical operators. Let’s say that we have 3 single-bit variables a, b and c which have to be randomized so that c is 1 only if both a and b are 1. This could be a solution:

Vtool Operator precedence and potential problems

But since equality operators have priority over logical operators, the expression in the constraint means “make sure that a is equal to c and that b is true” rather than “set c to be equal to a && b”. That is why b will be fixed to 1, which is potentially a problem since the cases when b is 0 never appear:

Vtool Operator precedence and potential problems

The solution is to simply use brackets in appropriate places:

Vtool Operator precedence and potential problems
Vtool Operator precedence and potential problems

Contact Us

Please, enter your details below. We will get back to you as fast as we can.

This website uses cookies to ensure you get the best experience on our website.

Get Cogita

Please, enter your details below. We will get back to you as fast as we can.

Thank you!

We will get in touch soon.

Get a Quote

Please, enter your details below. We will get back to you as fast as we can.