Menu
Coddy logo textTech

If Statement

CoddyのVerilogジャーニー「基礎」セクションの一部。レッスン 52/90。

if 文は、condition が true の場合にのみコードを実行する意思決定ブロックです。if 文は condition をチェックします。

If the condition is true (1), the code inside executes. If the condition is false (0), the code is skipped.

構文:

if (condition) begin
  // condition が true のときにコードが実行される
end

簡単な例

if (reset) begin
  count = 0;
end

この例では:

  • beginend は、コードブロックの開始終了を示すために使用されます
  • reset が 1(true)の場合、beginend の内部のコードが実行されます → count は 0 になります
  • reset が 0(false)の場合、内部のコードはスキップされます → 何も起こりません

beginend は、他のプログラミング言語における波かっこ { } と同じように機能します。これらはステートメントをまとめ、どのコードが if 条件に属するのかを Verilog が認識できるようにします。ここではステートメントが 1 つしかありませんが、一貫性を保つために beginend を使用するのは、依然として良い習慣です。

Alwaysブロック内のif文

always @(posedge clk) begin
  if (reset)
    count <= 0;
end

注: 1つの文の場合、beginend は省略できます。たとえば、上記の always ブロックでは文が1つしかないため、if の後に begin/end は必要ありません。

条件には任意の式を使用できる

if (a > b) begin
  max = a;
end

if (a && b) begin
  out = 1;
end

if (data == 8'hFF) begin
  match = 1;
end

重要なルール

ルール説明
condition は任意の式にできる0 以外(かつ既知)の値は true として扱われ、0 は false として扱われる
begin / end は複数の statement に必要他の言語における { } と同様
begin/end がない場合、続くのは 1 つの statement のみ次の行だけ
challenge icon

チャレンジ

行うこと:

  1. これを動作させるために、不足している if 文を追加してください。
  • enable1 のとき、outa & b と等しくなる必要があります
  • enable0 のとき、out0 のまま(変更されない)である必要があります

スターターコードは out = 0 を初期化し、両方のケースをテストします。

自分で試してみよう

module if_challenge;
  reg a, b, enable;
  reg out = 0;
  
  initial begin
    a = 1;
    b = 1;
    
    // テストケース 1: enable = 1
    enable = 1;
    // TODO: if文を追加 (out = a & b)
    $display("enable=1: out = %d (should be 1)", out);
    
    // テストケース 2: enable = 0
    enable = 0;
    out = 0; 
    // TODO: out は 0 のままであるべき
    $display("enable=0: out = %d (should be 0)", out);
    
    $finish;
  end
endmodule
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

基礎のすべてのレッスン

自分で練習してみよう: Verilogオンラインコンパイラ