Casts, Assignment Operators, Increment and Precedence
Use casts, +=, ++ and bare expressions without a surprise: know what each one changes in simulation and in gates.
You Will Be Able To
- Explain why
++and+=behave as blocking assignments and where that is safe. - Choose a size cast, a sign cast or a type cast for a given job.
- Predict how an expression without parentheses groups its operators.
- Fix a counter whose flag depends on the order of two blocks.
- Lesson
- R10.4
- Time
- 30 min
- Runs on
- Your browser
- Check
- 5 questions
An event counter raised a flag when its count had reached 3. The same file gave one answer on Icarus, another on Verilator and a third in the netlist. Every tool was within its rights.
at_three on Icarus 12, on Verilator 5.052 and in the design written with <=. The last row is what the flops do.- Cycle 2
Edge 4: the count becomes 3. Both simulators already show the flag, one cycle before the flops do.
- Cycle 3
Edge 5: the flops raise the flag now. They compared the count from before the edge.
- Cycle 5
Edge 7: the count leaves 3. Icarus keeps the flag, Verilator drops it, and the flops keep it for this last cycle.
The count is written with count++. The second block reads it at the same edge, and the order of the two is not defined.
++ and += Are Blocking Assignments
An assignment operator joins an operation and an assignment. a += b means a = a + b. i++ means i = i + 1. Each one is a blocking assignment: the variable changes at once.
| Operator | Means | Kind |
|---|---|---|
a += b, a -= b, a *= b | a = a + b, and so on | blocking |
a &= b, a |= b, a ^= b | a = a & b, and so on | blocking |
a <<= n, a >>= n, a >>>= n | a = a << n, and so on | blocking |
i++, ++i, i--, --i | i = i + 1 or i = i - 1 | blocking |
There is no nonblocking form. A program that ran acc += x; acc <<= 2; acc ^= 8'hff; acc -= 8'd1; from 5 and 3 printed acc=222. j = i++ took the old value and k = ++i the new one.
count that each block uses. The simulator may run the two blocks in either order.- Clock / reset
- Step
- Storage
- Clock
- Data
- A runs first
Block A changes
countat once. Block B then compares the new count, and the flag is one cycle early. - B runs first
Block B compares the old count, which is what the flops do. The standard allows either order.
- With <=
Write
count <= count + 4'd1.countnow changes after both blocks have run, so the order no longer matters.
Read the diagram as text
- Rising edge: both blocks wake
- Block A: count++
- Block B: at_three <= (count == 3)
- count: changes at once
- at_three: changes after both blocks
- Rising edge → Block A: wakes
- Rising edge → Block B: wakes
- Block A → count: writes now
- count → Block B: old or new?
- Block B → at_three: writes later
Lesson R2.1 is the full story of this race. ++ is the same race in two characters.
These operators are safe where blocking assignments are safe: in a for loop header, and for a temporary inside always_comb.
module ones8 (input logic [7:0] d, output logic [3:0] n);
always_comb begin
n = '0;
for (int i = 0; i < 8; i++) n += 4'(d[i]); // i++ steps the loop; += adds one bit
end
endmoduleCasts: Size, Sign and Type
A cast converts a value on purpose. The form is always target'(expression).
| Cast | Example with n = 4'b1010, sn = -3 | Result | What it does |
|---|---|---|---|
| size | 8'(n) | 10 | extends or truncates to 8 bits; pads an unsigned value with zeros |
| size of a signed value | 8'(sn) | -3 | pads a signed value with its sign bit |
| sign | signed'(n), $signed(n) | -6 | the same bits read as two's complement |
| sign | unsigned'(sn), $unsigned(sn) | 13 | the same bits read as unsigned |
| sign, then size | 8'(signed'(n)) | -6 | sign-extended, because the operand is signed |
| type | st_t'(2'd2) | DONE | a number becomes an enum value |
Measured on Icarus 12 and Verilator 5.052. A cast builds no gates: the enum cast alone synthesized to 0 cells.
An enum needs the type cast. Assign a plain 2-bit vector to an enum variable and the tools stop. Yosys says no implicit conversion from 'logic[1:0]' to 'st_t', and Lint reports ENUMVALUE.
The cast does not check the range. st_t'(2'd3) on an enum with three names stored 3, and .name() returned an empty string. $cast(st, d) does check at run time, but this flow refuses it: unsupported system task '$cast'.
Signed and Unsigned: The Same Adder
Two's complement was chosen so that one adder serves both readings. The gates for a + b do not know whether the bits are signed.
| 8-bit operation | Unsigned | Signed | Same gates? |
|---|---|---|---|
a + b into 8 bits | 34 cells, 14 levels | 34 cells, 14 levels | yes, cell for cell |
a + b into 9 bits | 38 cells, 15 levels | 37 cells, 15 levels | no: the ninth bit is a carry or a sign |
a < b | 29 cells, 9 levels | 29 cells, 10 levels | no: the top bit is weighed the other way |
a * b into 16 bits | 330 cells, 30 levels | 395 cells, 30 levels | no |
Measured on this flow. The sign changes how a value is extended, compared and multiplied. It does not change a same-width add.
So a sign cast costs nothing by itself. It changes which circuit the next operator builds. Lesson R1.4 has the rule for when an expression is signed.
Real Numbers Are for Constants
A real holds a floating-point number. A chip has no wire for it. Use reals to work out a constant before synthesis, and nowhere else.
| Expression | Result | Rule |
|---|---|---|
7 / 2 | 3 | two integers: the divide truncates |
7 / 2.0 | 3.5 | one real operand makes the expression real |
int i = 7 / 2.0; | 4 | a real assigned to an integer is rounded |
int'(2.5), int'(3.5), int'(-2.5) | 3, 4, -3 | the cast rounds, halves away from zero |
$rtoi(2.9) | 2 | this function truncates |
Measured on both simulators.
A real constant, turned into an integer
localparam real GAIN = 1.5;
localparam int K = int'(GAIN * 4.0); // 6
assign y = 8'((a * K) >> 2);
Builds: 35 cells and 10 levels. The real is gone before synthesis starts.
A real signal
real g;
always_comb begin
g = a * 1.5;
y = 8'(int'(g));
end
This flow stops with Feature unimplemented. Lint prints nothing for it.
Precedence: Who Binds First
With no parentheses, the operator higher in this ladder takes its operands first.
| Rank | Operators |
|---|---|
| 1 (first) | unary ! ~ - +, reductions & | ^, ++ -- |
| 2 | ** |
| 3 | * / % |
| 4 | + - |
| 5 | << >> <<< >>> |
| 6 | < <= > >= inside |
| 7 | == != === !== ==? !=? |
| 8, 9, 10 | &, then ^, then | |
| 11, 12 | &&, then || |
| 13 (last) | ? : |
Comparisons sit above the bitwise operators. That one fact causes most of the traps below.
| You wrote | It means | Measured | Lint |
|---|---|---|---|
a | b & c with 200, 100, 15 | a | (b & c) | 204; (a | b) & c is 12 | silent |
1 + 2 << 1 | (1 + 2) << 1 | 6; 1 + (2 << 1) is 5 | silent |
1 << 1 + 2 | 1 << (1 + 2) | 8 | silent |
!n == 4'd5 with n = 10 | (!n) == 4'd5 | 0; !(n == 4'd5) is 1 | WIDTHTRUNC, WIDTHEXPAND |
&q == 4'hf with q = 15 | (&q) == 4'hf | 0 | WIDTHEXPAND |
sel ? x : y + 10 | sel ? x : (y + 10) | 1 for 1 ? 1 : 2 + 10 | silent |
-2 ** 2 | (-2) ** 2 | 4 | silent |
3 < 2 < 1 | (3 < 2) < 1 | 1 | WIDTHEXPAND when the operands are 8-bit signals |
Measured on both simulators. Lint catches a trap only when it also makes two widths disagree.
The house rule is short. Put parentheses around every comparison and every shift that sits next to another operator.
The Lab: A Flag That Depends on Block Order
| Port | Direction | Width | Meaning |
|---|---|---|---|
| clk | input | 1 | clock |
| rst_n | input | 1 | reset, asynchronous, active-low |
| ev | input | 1 | 1 means one event at this edge |
| count | output | [3:0] | events counted since reset |
| at_three | output | 1 | registered: 1 for the cycle after count was 3 |
- Clock
- rising edge
- Reset
rst_nasynchronous, active-low:count0 andat_three0- Latency
at_threefollowscount == 3by one edge- Corner cases
- the edge where the count reaches 3, and the edge where it leaves 3. Done when: Run prints
at_threeas 0, 0, 0, 1, 1, 1 for edges 2 to 7, and Lint is silent
Run as shipped
The flag rises at edge 4, with the count. The brief says edge 5. At edge 7 the flag is still 1. On Verilator 5.052 the same file printed 0 at edge 7.
Ask Lint
Lint warns
BLKSEQon lines 10 and 11: "Blocking assignment '=' in sequential logic process". It namescount++as an assignment with=.Swap the blocks
Move the
at_threeblock above thecountblock and Run. The flag now rises at edge 5 and falls at edge 7. Nothing in the logic changed, only the order.Synthesize any of them
Each version is 15 cells, 5 flops and 3 levels. The flops compare the count from before the edge, whatever the simulators printed.
Fix the cause
Write the count block with
<=, as below. Run prints 0, 0, 0, 1, 1, 1 in either block order. Verilator printed the same lines, and Lint is silent.
The fix: nonblocking assignments for the count
always_ff @(posedge clk or negedge rst_n)
if (!rst_n) count <= 4'd0;
else if (ev) count <= count + 4'd1;Asked in interviews
Can you use
count++in analways_ffblock?It compiles, but
++is a blocking assignment. If any other clocked block readscountat the same edge, the result depends on simulation order. Usecount <= count + 1for registers.Do signed and unsigned adders differ in hardware?
Not for the same width: two's complement lets one adder serve both. The sign matters when a value is extended, compared, shifted right or multiplied.
What does
a & b == cmean?It means
a & (b == c), because the comparison binds before the bitwise AND. To compare the masked value, write(a & b) == c.
Try It
The bench sends three events, waits two edges and sends a fourth. It prints 1 ns after each edge.
At edge 4 Icarus ran the count block first, so the flag block compared the new count of 3. At edge 7 it ran the flag block first. Both orders are legal, so do not rely on either.
Synthesize reports 15 cells, 5 flops, 0 latches and 3 levels. The flag flop loads count == 3 from the count flops, which hold the value from before the edge.
Synthesize the design to measure its cells and inspect the mapped gates.
e2 ev=1 count=1 at_three=0 e3 ev=1 count=2 at_three=0 e4 ev=1 count=3 at_three=1 e5 ev=0 count=3 at_three=1 e6 ev=0 count=3 at_three=1 e7 ev=1 count=4 at_three=1Original design · 15 cells · 5 flip-flops · 0 latches · 3 logic levels. Synthesis uses Yosys; counts depend on the toolchain.
Read included file: tb.sv
`timescale 1ns/1ps
module tb;
logic clk = 0;
always #5 clk = ~clk; // rising edges at 5, 15, 25, ...
logic rst_n = 1; // falls at 1 ns, rises 1 ns after edge 1
int edge_n = -1;
always @(posedge clk) edge_n = edge_n + 1;
logic ev = 0;
logic [3:0] count;
logic at_three;
evt_count dut (.*);
task automatic tick();
@(posedge clk); #1;
if (rst_n) $display("e%0d ev=%b count=%0d at_three=%b", edge_n, ev, count, at_three);
endtask
initial begin
#1 rst_n = 0; tick(); tick(); rst_n = 1;
ev = 1; tick(); tick(); tick(); // three events: count reaches 3 at edge 4
ev = 0; tick(); tick();
ev = 1; tick(); // a fourth event at edge 7
$finish(0);
end
endmodule
Check Yourself
Common Mistakes
Wrong Put a sum inside a size cast to keep its carry, as 8'((a + b) >> 1).
The operand of a cast is sized on its own, so the 8-bit sum loses the carry before the shift.
Fix Widen an operand inside the cast: 8'((9'(a) + b) >> 1) gave 150 for 200 and 100, where the first form gave 22.
logic [7:0] a, b, avg;
assign avg = 8'((a + b) >> 1);logic [7:0] a, b, avg;
assign avg = 8'((9'(a) + b) >> 1);Wrong Cast any number into an enum and trust the result.
A static cast does no range check, so the variable can hold a value that has no name.
Fix Check the range before the cast, or give the case on that enum a default arm.
Wrong Write a gain as a real signal and convert at the end.
This flow builds no hardware for a real variable and stops, while Lint says nothing.
Fix Keep reals in localparam constants, turn them into integers there, and do the signal math in integers.
Wrong Write -x ** 2 or a < b < c as you would on paper.
Unary minus binds before **, and a < b gives 0 or 1, which is then compared with c.
Fix Write -(x ** 2) and (a < b) && (b < c).
Remember
++,--,+=and the other assignment operators are blocking. Keep them out of registers that another block reads.- A size cast pads with zeros or with the sign, as the operand's type says. A sign cast changes the reading and no bits.
- A cast builds no gates. An enum cast does no range check, and
$castis not for synthesis. - A same-width add is the same gates signed or unsigned. Extension, compare and multiply are not.
- Comparisons bind before
&,^and|, and unary operators bind before everything. Use parentheses.