Menu
Coddy logo textTech

if - else 文

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

if-else 文を使用すると、条件に基づいて2つの異なるアクションのいずれかを選択できます。条件が真(true)の場合、一方のブロックが実行されます。偽(false)の場合、もう一方のブロックが実行されます。

if-else文は、コードに判断ポイントを与えます。条件が真(true)であれば1つのことを行い、条件が偽(false)であれば別のことを行います。

構文:

if (condition) begin
  // 条件が真 (1) の場合に実行されます
end else begin
  // 条件が偽 (0) の場合に実行されます
end

簡単な例

if (reset) begin
  count = 0;
end else begin
  count = count + 1;
end
  • reset が 1 の場合 → count は 0 になります
  • reset が 0 の場合 → count は 1 増加します

複数のステートメント

複数のステートメントがある場合は、beginendを使用します:

if (enable) begin
  out = data_in;
  valid = 1;
end else begin
  out = 0;
  valid = 0;
end

複数の条件を持つ If-Else

if-else 文を連結することができます:

if (a > b) begin
  max = a;
end else if (b > a) begin
  max = b;
end else begin
  max = a;  // a と b は等しい
end

重要なルール

ルール説明
else は任意ですelse なしの if を記述できます
else は最も近い if に属します入れ子(ネスト)に注意してください
複数のステートメントには begin/end を使用します2行以上の場合は必須です
challenge icon

チャレンジ

実行すること:

  1. これを動作させるために、不足している if-else 文を追加してください。
  2. enable が 1 のとき、outa & b と等しくなる必要があります。
  3. enable が 0 のとき、outa | b と等しくなる必要があります。

チートシート

if-else文は、条件に基づいて2つのブロックのいずれかを実行します:

if (condition) begin
  // 条件が真(1)のときに実行
end else begin
  // 条件が偽(0)のときに実行
end

else ifを使用して複数の条件を連結します:

if (a > b) begin
  max = a;
end else if (b > a) begin
  max = b;
end else begin
  max = a; // aとbは等しい
end
  • elseは任意です
  • ブロック内に複数のステートメントがある場合は、begin/endを使用します
  • elseは常に最も近いifに属します

自分で試してみよう

module ifelse_challenge;
  reg a, b, enable;
  reg out;
  
  initial begin
    a = 1;
    b = 0;
    enable = 1;
    
    // TODO: if-else文を追加
    // enableが1の場合: out = a & b
    // それ以外の場合: out = a | b
    
    $display("out = %d (should be 0 because 1&0=0)", out);
    $finish;
  end
endmodule
quiz icon腕試し

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

基礎のすべてのレッスン