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.

One Counter, Three Answers for the FlagThe lab bench, 1 ns after edges 2 to 7. The three bottom rows are at_three on Icarus 12, on Verilator 5.052 and in the design written with <=. The last row is what the flops do.
012345clkevcount1234at_three (Icarus)at_three (Verilator)at_three (flops)earlydiffer
Scroll horizontally ↔
  1. Cycle 2

    Edge 4: the count becomes 3. Both simulators already show the flag, one cycle before the flops do.

  2. Cycle 3

    Edge 5: the flops raise the flag now. They compared the count from before the edge.

  3. 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.

OperatorMeansKind
a += b, a -= b, a *= ba = a + b, and so onblocking
a &= b, a |= b, a ^= ba = a & b, and so onblocking
a <<= n, a >>= n, a >>>= na = a << n, and so onblocking
i++, ++i, i--, --ii = i + 1 or i = i - 1blocking

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.

Two Blocks at One Clock EdgeArrows show the value of count that each block uses. The simulator may run the two blocks in either order.
  • Clock / reset
  • Step
  • Storage
  • Clock
  • Data
Two blocks at one clock edgeArrows show the value of `count` that each block uses. The simulator may run the two blocks in either order. clock reset Rising edge both blocks wake step Block A count++ step Block B at_three <= (count== 3) storage count changes at once storage at_three changes after bothblocks wakeswakeswrites nowold or new?writes later
  1. clock reset Rising edgeboth blocks wake
    • wakes → Block A
    • wakes → Block B
  2. step Block Acount++
    • writes now → count
  3. storage countchanges at once
    • old or new? → Block B
  4. step Block Bat_three <= (count == 3)
    • writes later → at_three
  5. storage at_threechanges after both blocks
  1. A runs first

    Block A changes count at once. Block B then compares the new count, and the flag is one cycle early.

  2. B runs first

    Block B compares the old count, which is what the flops do. The standard allows either order.

  3. With <=

    Write count <= count + 4'd1. count now 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.

Synthesize reports 26 cells and 10 levels. The loop is unrolled into a chain of adders, with no storage.
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
endmodule

Casts: Size, Sign and Type

A cast converts a value on purpose. The form is always target'(expression).

CastExample with n = 4'b1010, sn = -3ResultWhat it does
size8'(n)10extends or truncates to 8 bits; pads an unsigned value with zeros
size of a signed value8'(sn)-3pads a signed value with its sign bit
signsigned'(n), $signed(n)-6the same bits read as two's complement
signunsigned'(sn), $unsigned(sn)13the same bits read as unsigned
sign, then size8'(signed'(n))-6sign-extended, because the operand is signed
typest_t'(2'd2)DONEa 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 operationUnsignedSignedSame gates?
a + b into 8 bits34 cells, 14 levels34 cells, 14 levelsyes, cell for cell
a + b into 9 bits38 cells, 15 levels37 cells, 15 levelsno: the ninth bit is a carry or a sign
a < b29 cells, 9 levels29 cells, 10 levelsno: the top bit is weighed the other way
a * b into 16 bits330 cells, 30 levels395 cells, 30 levelsno

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.

ExpressionResultRule
7 / 23two integers: the divide truncates
7 / 2.03.5one real operand makes the expression real
int i = 7 / 2.0;4a real assigned to an integer is rounded
int'(2.5), int'(3.5), int'(-2.5)3, 4, -3the cast rounds, halves away from zero
$rtoi(2.9)2this 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.

RankOperators
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 wroteIt meansMeasuredLint
a | b & c with 200, 100, 15a | (b & c)204; (a | b) & c is 12silent
1 + 2 << 1(1 + 2) << 16; 1 + (2 << 1) is 5silent
1 << 1 + 21 << (1 + 2)8silent
!n == 4'd5 with n = 10(!n) == 4'd50; !(n == 4'd5) is 1WIDTHTRUNC, WIDTHEXPAND
&q == 4'hf with q = 15(&q) == 4'hf0WIDTHEXPAND
sel ? x : y + 10sel ? x : (y + 10)1 for 1 ? 1 : 2 + 10silent
-2 ** 2(-2) ** 24silent
3 < 2 < 1(3 < 2) < 11WIDTHEXPAND 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

Design brief
PortDirectionWidthMeaning
clkinput1clock
rst_ninput1reset, asynchronous, active-low
evinput11 means one event at this edge
countoutput[3:0]events counted since reset
at_threeoutput1registered: 1 for the cycle after count was 3
Clock
rising edge
Reset
rst_n asynchronous, active-low: count 0 and at_three 0
Latency
at_three follows count == 3 by one edge
Corner cases
the edge where the count reaches 3, and the edge where it leaves 3. Done when: Run prints at_three as 0, 0, 0, 1, 1, 1 for edges 2 to 7, and Lint is silent
  1. 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.

  2. Ask Lint

    Lint warns BLKSEQ on lines 10 and 11: "Blocking assignment '=' in sequential logic process". It names count++ as an assignment with =.

  3. Swap the blocks

    Move the at_three block above the count block and Run. The flag now rises at edge 5 and falls at edge 7. Nothing in the logic changed, only the order.

  4. 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.

  5. 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
The netlist does not change: 15 cells, 5 flops, 3 levels. Only the simulation now agrees with it.
  always_ff @(posedge clk or negedge rst_n)
    if (!rst_n)  count <= 4'd0;
    else if (ev) count <= count + 4'd1;
Asked in interviews
  1. Can you use count++ in an always_ff block?

    It compiles, but ++ is a blocking assignment. If any other clocked block reads count at the same edge, the result depends on simulation order. Use count <= count + 1 for registers.

  2. 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.

  3. What does a & b == c mean?

    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.

RTLIcarus Verilog · in your browser · Lint: Verilator service · Synthesize: Yosys service
Edit the design, then Run, Lint or Synthesize
Expected: 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=1

Original 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

Predict the outputOne clocked block increments n with ++ and then tests it. The bench gives three rising edges. What does it print?
module tb;
  logic       clk = 0;
  logic [3:0] n = 0;
  logic       hit = 0;
  always @(posedge clk) begin
    n++;
    if (n == 4'd3) hit <= 1'b1;
  end
  initial begin
    repeat (3) begin #1 clk = 1; #1 clk = 0; end
    $display("n=%0d hit=%b", n, hit);
    $finish(0);
  end
endmodule
Spot the bugEach option should set all to 1 only when all four bits of q are 1. The bench tries all 16 values. Which option fails?
ConceptOn this flow, an 8-bit a + b was synthesized twice: with unsigned ports and with signed ports. What did the counts show?
ConceptIn the lab, moving the at_three block above the count block changed what Icarus printed. What did the move change in the netlist?
ConceptA design needs the constant 0.75 times 256 as an integer parameter. Which line is safe for synthesis on this flow?

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.

Before
logic [7:0] a, b, avg;
assign avg = 8'((a + b) >> 1);
After
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 $cast is 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.

Practice

Report a problem with this page