C:C言語のプリミティブデータ型と明示的な書式指定子
C•変数

C言語のプリミティブデータ型と明示的な書式指定子

C言語の変数は、厳密なバイト幅とアライメント規則を持つメモリ上の型付き領域です。C には自動の文字列補間がないため、printf の書式指定子(%d, %f, %.2f, %c, %lu, %s)によって生のバイナリメモリをどのように解釈・表示するかを明示的に指定します。

構文

int count = 42; float temp = 98.6f; double precise = 3.14159265; char grade = 'A'; unsigned long bytes = 1048576UL; printf("%d | %.2f | %c | %lu\n", count, temp, grade, bytes);

パラメータと値

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

パラメータ型説明
%d / %iFormat Specifier符号付き32ビット10進整数(現代的な環境では4バイト)。
%f / %.NfFormat Specifier浮動小数点数。.N で小数点以下の桁数を厳密に指定します。
%lfFormat Specifier倍精度64ビット浮動小数点数(8バイト)。
%cFormat SpecifierASCII 整数としてエンコードされた1バイト文字。
%luFormat Specifierバイトサイズや64ビットカウント向けの符号なし長整数。

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

Compilra で実行可能

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

#include <stdio.h>

int main(void) {
    // 1. Primitive integer and character data types
    int activeSockets = 128;
    char systemTier = 'A';
    unsigned long memoryAllocatedBytes = 1048576UL;

    // 2. Floating-point types with defined precision
    float cpuTemperature = 48.35f;
    double benchmarkScore = 99.87654;

    // 3. Explicit printf format specifiers
    printf("=== GCC C Memory Allocation & Formats ===\n");
    printf("Active Sockets:   %d (sizeof: %lu bytes)\n", activeSockets, sizeof(activeSockets));
    printf("Cluster Tier:     %c (ASCII code: %d)\n", systemTier, systemTier);
    printf("Allocated Memory: %lu bytes (sizeof: %lu bytes)\n", memoryAllocatedBytes, sizeof(memoryAllocatedBytes));
    printf("CPU Temperature:  %.2f deg C\n", cpuTemperature);
    printf("Benchmark Score:  %.4f\n", benchmarkScore);

    return 0;
}
期待される出力:
=== GCC C Memory Allocation & Formats ===
Active Sockets:   128 (sizeof: 4 bytes)
Cluster Tier:     A (ASCII code: 65)
Allocated Memory: 1048576 bytes (sizeof: 8 bytes)
CPU Temperature:  48.35 deg C
Benchmark Score:  99.8765

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

  • 5〜7行目: スタック上に整数、char、unsigned long の基本型変数を確保します。
  • 10〜11行目: 単精度 float(4バイト)と倍精度 double(8バイト)を初期化します。
  • 14〜19行目: 各変数を書式指定子(%d, %c, %lu, %.2f, %.4f)に対応付け、sizeof でメモリサイズを評価します。

重要ポイント

  • C言語は実行時の型情報参照を行わないため、printf はスタックから何バイト読み取るかを書式指定子のみに依存します。
  • sizeof はバイト数を size_t として返すコンパイル時演算子で、%lu または %zu で出力します。
  • C の文字は ASCII 値を格納する1バイト整数であり、%c は文字を表示し、%d は10進数の ASCII コードを表示します。
  • %.2f の .N 修飾子は、デフォルトの6桁ではなくちょうど N 桁の小数精度へ丸めて表示します。

よくある間違い: 型の合わない書式指定子で破損したスタックメモリを読む

float を %d に渡したり整数を %f に渡したりすると、printf がビット列を誤った型として解釈し、0 や不定値、予期しない NaN が出力されます。

❌ 誤り
float val = 48.5f;
printf("Value: %d\n", val); // Bug: prints corrupted integer!
✅ 正しい例
float val = 48.5f;
printf("Value: %.2f\n", val); // Correct: matches float decoding

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

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

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

C オンラインコンパイラ