# Verilog ternary operator - verilog

This is a discussion on Verilog ternary operator - verilog ; Hi All.. Can ny one explain the difference between these two pieces of code at the output of simulator? reg y; always @ (a or b or select) if (select) y = a; else y = b; AND wire t ...

1. ## Verilog ternary operator

Hi All..

Can ny one explain the difference between these two pieces of code at
the output of simulator?

reg y;

always @ (a or b or select)
if (select)
y = a;
else
y = b;

AND

wire t = (select ? a : b);

To put it in a easier way, What is the difference between a ternary
operator and if-else conditional statement?

Sailaja.

2. ## Re: Verilog ternary operator

On Mon, 27 Aug 2007 10:21:49 -0000,
Sailu <shailaja.akkem@gmail.com> wrote:

>reg y;
>
>always @ (a or b or select)
> if (select)
> y = a;
> else
> y = b;
>
> AND
>
>wire t = (select ? a : b);
>
> To put it in a easier way, What is the difference between a ternary
>operator and if-else conditional statement?

One obvious difference you've already seen: if you use a procedural
"if" you must, of course, drive a variable ("reg") because the
assignment is made from procedural code. But ?: forms an
expression, which can easily be used as the right-hand side
of a continuous "assign", so driving a net ("wire") if you wish.

The other big difference is what happens if "select" is unknown
(X or Z). An if() statement, given an unknown condition, takes
the false (else) branch. A conditional operator, on the
other hand, acts much more like a hardware multiplexer.
Try this example to see the difference.

reg [3:0] result_if, result_cond;
initial begin
if (1'bx)
result_if = 4'b0110;
else
result_if = 4'b0101;
result_cond = 1'bx ? 4'b0110 : 4'b0101;
\$display("if: %b cond: %b", result_if, result_cond);
end

Having said all this, it is probably fair to say that there
is NO functional difference when the two different constructs
are used in synthesis.
--
Jonathan Bromley, Consultant

DOULOS - Developing Design Know-how
VHDL * Verilog * SystemC * e * Perl * Tcl/Tk * Project Services

Doulos Ltd., 22 Market Place, Ringwood, BH24 1AW, UK
jonathan.bromley@MYCOMPANY.com
http://www.MYCOMPANY.com

The contents of this message may contain personal views which
are not the views of Doulos Ltd., unless specifically stated.

3. ## Re: Verilog ternary operator

Sailu wrote:

> Can ny one explain the difference between these two pieces of code at
> the output of simulator?

> reg y;
> always @ (a or b or select)
> if (select)
> y = a;
> else
> y = b;

> AND

> wire t = (select ? a : b);

There are many things that can be written in both behavioral
verilog (always blocks) and structural verilog (continuous
assignment).

Personally, I prefer structural verilog except for FF's which are
normally written in behavioral form. As someone else said,
there may be differences for X and Z values, but they should
both synthesize to the same logic.

-- glen