#136. 条件运算符
条件运算符
题目描述
Verilog中有一个跟C语言中类似的三目条件运算符( ? : ),其语法格式为:
(condition ? if_true : if_false)
该表达式可以用于为其它信号赋值,例如:signal = condition ? if_true : if_false;
该语句等同于:
if(condition) signal = if_true;
else signal = if_false;
因涉及到3个操作数,并且能实现条件运算的功能,因此称为三目条件运算符。
下面是几个使用该运算符的例子:
(0 ? 3 : 5) // 条件为假,因此表达式的值为5
(sel ? b : a) // 二选一选择器
always @(posedge clk) // 触发器
q <= toggle ? ~q : q;
always @(*) // 有限状态机(FSM)
case (state)
A: next = w ? B : A;
B: next = w ? A : B;
endcase
assign out = ena ? q : 1'bz; // 三态门
((sel[1:0] == 2'h0) ? a : (sel[1:0] == 2'h1) ? b : c ) //嵌套使用
试设计一计算最小值功能的Verilog模块,给定四个无符号数,求最小值。提示:
- 可以综合使用比较运算符(< or >)和条件运算符(? :)。
- 有必要的话,可以定义中心变量
输入格式
8bit a,b,c,d
输出格式
8bit min, 为 a,b,c,d的最小值
示例代码
module top (
input [7:0] a, b, c, d,
output [7:0] min);
endmodule