# If Statement and Case Statement ###### tags: `Digital IC Design` [回到主頁面](https://hackmd.io/@derek8955/BkK2Nb5Jo/https%3A%2F%2Fhackmd.io%2FdpcBlBL8TlShpQ-wSi9Quw) > 這兩種 statement 只能用在 behavioral modeling - 語法與 C 很像 - If 跟 Case 大致上雷同,但因為 If 有優先權問題,所以兩個 statement 所描述的電路會有所不同 ```verilog= module IF( e, sel, a, b, c, d ); output reg e; input [1:0] sel; input a, b, c, d; always @( * ) begin if( sel == 2'd3 ) e = a; else if( sel == 2'd2 ) e = b; else if( sel == 2'd1 ) e = c; else e = d; end endmodule module CASE( e, sel, a, b, c, d ); output reg e; input [1:0] sel; input a, b, c, d; always @( * ) begin case(sel) 2'd3: e = a; 2'd2: e = b; 2'd1: e = c; default: e = d; endcase end endmodule ``` |![](https://i.imgur.com/rUg62Mr.png)|![](https://i.imgur.com/G3gpd71.png)| |:---:|:---:| | If statement |case statement| ```verilog= // if statement 要考慮 path 是否太長 module example(); reg [1:0] cnt; ... ... ... // long path if( cnt == 3 ) result = a; else if( cnt == 2 ) result = b; else if( cnt == 1 ) result = c; else result = d; // cnt == 0 // short path if( cnt[1] == 1 ) begin // cnt[1] 意即 cnt signal 的第1個 bit if( cnt[0] ) result = a; // cnt[0] 意即 cnt signal 的第0個 bit // 在 if statement 中, "cnt[0]" 相同於 "cnt[0] == 1" else result = b; end else begin if( cnt[0] ) result = c; else result = d; end endmodule ```