Concept Flow - Conditional (ternary) operator
Evaluate condition
Yes
Use true expression
Result
No
Use false expression
Result
The ternary operator checks a condition; if true, it returns the first value, else the second.
assign out = (sel) ? a : b;
| Step | Condition (sel) | True Expression (a) | False Expression (b) | Result (out) |
|---|---|---|---|---|
| 1 | 0 | 5 | 10 | 10 |
| 2 | 1 | 5 | 10 | 5 |
| 3 | 0 | 3 | 7 | 7 |
| 4 | 1 | 8 | 2 | 8 |
| Exit | - | - | - | End of evaluation |
| Variable | Start | After 1 | After 2 | After 3 | After 4 | Final |
|---|---|---|---|---|---|---|
| sel | undefined | 0 | 1 | 0 | 1 | 1 |
| a | undefined | 5 | 5 | 3 | 8 | 8 |
| b | undefined | 10 | 10 | 7 | 2 | 2 |
| out | undefined | 10 | 5 | 7 | 8 | 8 |
Syntax: condition ? true_expr : false_expr; Evaluates condition; if true, returns true_expr else false_expr. Used for simple if-else in one line. In Verilog, commonly used in assign statements. Result depends on condition value at runtime.
condition ? value_if_true : value_if_false do in Verilog?out after this Verilog code runs?wire [3:0] a = 4'd7; wire [3:0] b = 4'd10; wire [3:0] out; assign out = (a > b) ? a : b;
assign result = (x == 1) ? 5 : ;
final_out? wire [3:0] a = 4'd3; wire [3:0] b = 4'd7; wire [3:0] c = 4'd5; wire [3:0] final_out; assign final_out = (a > b) ? ((b > c) ? b : c) : ((a > c) ? a : c);
Pass the test and this pattern moves unknown