C:C における短絡評価の三項ロジックと条件式
C•条件分岐

C における短絡評価の三項ロジックと条件式

C の論理積 (&&) と論理和 (||) は左から右への厳密な短絡評価を保証します。&& の左オペランドが 0 (偽) の場合、右オペランドは一切実行されないため防御的ポインタガードに不可欠です。三項条件演算子 (? :) と組み合わせることで、効率的なインライン式パイプラインを構築できます。

構文

if (ptr != NULL && *ptr > 0) { /* safe dereference */ } const char* tier = (score >= 90) ? "EXCELLENT" : (score >= 70) ? "PASS" : "FAIL";

パラメータと値

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

パラメータ型説明
&& (Logical AND)Operatorまず左を評価し、左オペランドが 0 (false) なら即座に停止します。
|| (Logical OR)Operatorまず左を評価し、左オペランドが 0 以外 (true) なら即座に停止します。
? : (Ternary)Operatorインライン条件式:condition ? value_if_true : value_if_false。

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

Compilra で実行可能

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

#include <stdio.h>

int simulateHealthCheck(int* pingCount) {
    (*pingCount)++;
    return 1;
}

int main(void) {
    int healthPings = 0;
    int isServiceOnline = 1;
    int errorCount = 0;

    // 1. Short-circuit evaluation demonstration
    // Because isServiceOnline is 1 (true), simulateHealthCheck is evaluated
    if (isServiceOnline && simulateHealthCheck(&healthPings)) {
        printf("[OK] Primary health probe responded (Pings: %d)\n", healthPings);
    }

    // 2. Short-circuit guard: left is 0, so right function is skipped entirely
    int isBackupOnline = 0;
    if (isBackupOnline && simulateHealthCheck(&healthPings)) {
        printf("[WARN] Backup probe executed\n");
    } else {
        printf("[SKIP] Backup probe skipped without invoking side effects (Pings: %d)\n", healthPings);
    }

    // 3. Chained ternary logic pipeline
    int loadScore = 84;
    const char* clusterTier = (loadScore >= 90) ? "CRITICAL"
                            : (loadScore >= 75) ? "HEAVY_LOAD"
                            : (loadScore >= 40) ? "BALANCED"
                            : "IDLE";

    // 4. Inline ternary string formatting
    printf("Cluster Tier: %s (Status: %s)\n",
           clusterTier,
           (errorCount == 0) ? "HEALTHY" : "DEGRADED");

    return 0;
}
期待される出力:
[OK] Primary health probe responded (Pings: 1)
[SKIP] Backup probe skipped without invoking side effects (Pings: 1)
Cluster Tier: HEAVY_LOAD (Status: HEALTHY)

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

  • 15-18 行目: 左オペランド isServiceOnline が真であるため simulateHealthCheck を実行します。
  • 21-26 行目: 短絡評価:isBackupOnline が 0 のため右側の関数は呼ばれず、healthPings は 1 のままになります。
  • 29-34 行目: 冗長な if/else 文を使わずにネストされた三項式チェーンで負荷状態を判定します。
  • 36-39 行目: メモリ割り当てなしで状態文字列を得るため printf の引数リスト内で直接インライン三項演算子を使用します。

重要ポイント

  • 短絡評価は ISO C 規格で保証されており、左オペランドが先に評価され、必要な場合のみ右オペランドが評価されます。
  • (ptr != NULL && *ptr == target) のような防御的ポインタガードは、参照外しの前に安全に中断することでセグメンテーションフォールトを防ぎます。
  • C では 0 以外の整数はすべて論理的に真とみなされ、整数 0 のみが厳密に偽となります。
  • 三項演算子は統一された型の式を返すため、不変な const 代入に最適です。

よくある間違い: 条件式内での誤った代入:if (state = 1)

if 文内で単一の = を使うと値が代入され、その値(0 以外)が評価されるため、以前の状態に関係なく常に分岐が実行されてしまいます。

❌ 誤り
if (isServiceOnline = 0) { /* Accidentally zeroes variable and evaluates to false! */ }
✅ 正しい例
if (isServiceOnline == 0) { /* Proper equality comparison */ }

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

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

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

C オンラインコンパイラ