C:C における While と Do-While の条件付き反復パイプライン
C•ループ

C における While と Do-While の条件付き反復パイプライン

C 言語には本体に入る前に条件を確認する前判定 while ループと、最低 1 回の実行を保証する後判定 do-while ループがあります。ハードウェアのリトライ処理、ストリーム読み取り、キューワーカーの状態機械には不可欠です。

構文

while (hasWork) { processItem(); } do { attemptConnection(); } while (retryCount < maxRetries);

パラメータと値

この構文の主な構成要素と指定可能な値:

パラメータ型説明
while (cond)Loop Control前判定ループ:条件評価に応じて 0 回以上実行されます。
do ... while (cond);Loop Control後判定ループ:条件を評価する前に少なくとも 1 回の実行を保証します。

そのまま実行できるコード例

Compilra で実行可能

C をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:

#include <stdio.h>

int main(void) {
    // 1. While loop: Logarithmic queue worker pipeline
    printf("=== While Loop: Worker Queue Processing ===\n");
    int pendingJobs = 16;
    int processedBatches = 0;

    while (pendingJobs > 1) {
        printf("Batch %d: Processing %d jobs (splitting queue)\n", ++processedBatches, pendingJobs);
        pendingJobs /= 2; // Halves the work each iteration
    }
    printf("Final standalone job resolved. Remaining: %d\n", pendingJobs);

    // 2. Do-While loop: Network connection retry state machine
    printf("\n=== Do-While Loop: Connection Handshake Pipeline ===\n");
    int connectionAttempt = 0;
    int maxAttempts = 3;
    int handshakeEstablished = 0;

    do {
        connectionAttempt++;
        printf("Attempt #%d: Sending SYN packet to gateway...\n", connectionAttempt);

        // Simulate successful handshake on attempt 3
        if (connectionAttempt == 3) {
            handshakeEstablished = 1;
            printf("Attempt #%d: ACK received! Connection established.\n", connectionAttempt);
        } else {
            printf("Attempt #%d: Timeout. Backing off...\n", connectionAttempt);
        }
    } while (!handshakeEstablished && connectionAttempt < maxAttempts);

    printf("Handshake Pipeline Terminated: %s\n",
           handshakeEstablished ? "SUCCESS (200 OK)" : "FAILED (504 Gateway Timeout)");

    return 0;
}
期待される出力:
=== While Loop: Worker Queue Processing ===
Batch 1: Processing 16 jobs (splitting queue)
Batch 2: Processing 8 jobs (splitting queue)
Batch 3: Processing 4 jobs (splitting queue)
Batch 4: Processing 2 jobs (splitting queue)
Final standalone job resolved. Remaining: 1

=== Do-While Loop: Connection Handshake Pipeline ===
Attempt #1: Sending SYN packet to gateway...
Attempt #1: Timeout. Backing off...
Attempt #2: Sending SYN packet to gateway...
Attempt #2: Timeout. Backing off...
Attempt #3: Sending SYN packet to gateway...
Attempt #3: ACK received! Connection established.
Handshake Pipeline Terminated: SUCCESS (200 OK)

動作のしくみ: ステップ解説

  • 9-14 行目: 前判定 while ループが本体前に pendingJobs > 1 を確認し、毎周回ジョブ数を半減させます。
  • 22-34 行目: do-while により再試行条件の評価前に試行 #1 が即座に実行されることを保証します。
  • 34 行目: 複合条件 (!handshakeEstablished && connectionAttempt < maxAttempts) を評価します。

重要ポイント

  • 初期判定が false (0) なら while ループは 0 回実行されるため、すでに作業が終わっている場合に最適です。
  • do-while ループは必ず少なくとも 1 回本体を実行するため、I/O メニューやソケットハンドシェイク、入力検証の標準パターンです。
  • 無限ループを防ぐため、ループ本体内で必ず状態を更新(例:pendingJobs /= 2 や connectionAttempt++)してください。
  • do-while 構文では while (condition); の末尾に必須のセミコロンが付く点に注意してください。

よくある間違い: do-while ループ末尾のセミコロンを省略する

for や while とは異なり、do-while は while 条件の閉じ括弧の後に終端セミコロンが必須です。省略すると構文コンパイルエラーになります。

❌ 誤り
do { doWork(); } while (retryCount < 3) // Missing semicolon compilation error!
✅ 正しい例
do { doWork(); } while (retryCount < 3); // Valid terminating semicolon

関連するCチュートリアルとコンパイラ

Compilra で C を実行・テストする

Compilraのクラウドコンパイラ上で事前設定した標準入力 (stdin) を使ってこのコードを実行できます。

C オンラインコンパイラ