Difficulty: Easy · Puzzle 3 of 6 · Topic: Queue and Array Puzzles
What values are returned by `pop_front` and `pop_back` on an empty queue?
module p3;
int q[$];
int a, b;
initial begin
a = q.pop_front();
b = q.pop_back();
$display("a=%0d b=%0d size=%0d", a, b, q.size());
end
endmoduleSV returns default value of element type when popping from an empty queue.
1) Queue starts empty.
2) `pop_front()` returns default `int` value 0 when queue is empty.
3) `pop_back()` on still-empty queue also returns 0.
4) Queue size remains 0.Answer: a=0, b=0, size=0
Checked by running the code in Verilator 5 and Icarus Verilog 13; the printed output supports the answer above. A conforming tool returns the default value 0 for int. Icarus returns x for an empty-queue pop of int, which the LRM does not call for (it requires the default value 0).
Popping an empty queue is not a fatal error: it returns the element type's default (0 for `int`), and some tools only warn (Icarus even returns x for an int queue, which is non-conforming).
How would behavior differ for `string q[$]` when popping empty? Model answer: it returns the empty string ""; for a 4-state element type such as `logic [3:0]` it returns x (run on Icarus: [] and xxxx).
I would say that popping an empty queue is not fatal and it returns the default value of the element type, which is 0 for an int. So both pops give 0 and the size stays 0. The trap is that tools differ: some only warn, and Icarus even returns x for an int queue, which is not what the standard says. I would check the size before every pop in real code.