Verilog question mark (?) operator

I'm trying to translate a Verilog program into VHDL and have stumbled across a statement where a question mark (?) operator is used in the Verilog program.

The following is the Verilog code;

1 module music(clk, speaker); 2 input clk; 3 output speaker; 4 parameter clkdivider = 25000000/440/2; 5 reg [23:0] tone; 6 always @(posedge clk) tone <= tone+1; 7 reg [14:0] counter; 8 always @(posedge clk) if(counter==0) counter <= (tone[23] ? clkdivider-1 : clkdivider/2-1); else counter <= counter-1; 9 reg speaker; 10 always @(posedge clk) if(counter==0) speaker <= ~speaker; 11 endmodule 

I don't understand the 8th line, could anyone please shed some light on this? I've read on the asic-world website that the question mark is the Verilog alternate for the Z character. But I don't understand why it's being used in this context.

Kind regards

3 Answers

That's a ternary operator. It's shorthand for an if statement

Format:

condition ? if true : if false 

Example:

tone[23] ? clkdivider-1 : clkdivider/2-1 

Translates to something like (not correct syntax but I think you'll get it):

if tone[23] is 1, counter = clkdivider-1 else counter = clkdivider/2-1 

Here are two examples of a 2 to 1 MUX using if statement and ternary operator.

On the asic-world website, it is covered under Conditional Operators

1

Another way of writing, e.g. the following Verilog:

q <= tone[23] ? clkdivider-1 : clkdivider/2-1; 

in VHDL would be:

q <= clkdivider-1 when tone[23] else clkdivider/2-1; 
5

Think of it as a MUX, before the ? is the selection bit and on two sides of : are the inputs

2

You Might Also Like