C•関数
C 言語の関数プロトタイプ宣言と実行スタックフレーム
C コンパイラはファイルを上から下へ線形に読み取ります。関数プロトタイプ宣言は完全な定義の前にシグネチャ(戻り値型と引数リスト)を前方宣言し、定義より先に関数を呼び出せるようにします。実行時には関数呼び出しごとにローカル変数や戻りアドレスを持つスタックフレームが積まれます。
構文
int processMetrics(int inputVal, int* outStatus);
int main(void) {
int status = 0;
int res = processMetrics(10, &status);
}
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| Prototype | Forward Declaration | main() の前に、関数名・戻り値型・引数の型をコンパイラへ登録します。 |
| Pass-by-Value | Memory Model | C は新しく積まれたスタックフレームのスロットへ引数をコピーします。 |
| Pointer Output | Memory Address | &var ポインタを渡し、呼び出し先フレームから呼び出し元スタックを書き換え可能にします。 |
そのまま実行できるコード例
Compilra で実行可能C をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
#include <stdio.h>
// 1. Forward function prototypes (Compiler Signature Registration)
int processTransaction(int amount, float feeRate, int* outFee);
void displayFrameState(const char* frameName, int depth);
int main(void) {
displayFrameState("main() [Stack Base Frame]", 1);
int transactionAmount = 250;
float serviceFeeRate = 0.04f;
int calculatedFee = 0;
printf("Initiating Transaction: $%d\n", transactionAmount);
// Call function: passes pointer &calculatedFee to allow caller mutation
int netTotal = processTransaction(transactionAmount, serviceFeeRate, &calculatedFee);
printf("Calculated Fee: $%d\n", calculatedFee);
printf("Net Total Dispatched: $%d\n", netTotal);
displayFrameState("main() [Terminating Frame]", 1);
return 0;
}
// 2. Callee Function Implementation
int processTransaction(int amount, float feeRate, int* outFee) {
displayFrameState("processTransaction() [Child Activation Frame]", 2);
// Compute fee and mutate caller frame via pointer dereference
*outFee = (int)(amount * feeRate);
int total = amount + *outFee;
return total;
}
void displayFrameState(const char* frameName, int depth) {
printf(" [CALL STACK Depth %d] -> %s\n", depth, frameName);
}期待される出力:
[CALL STACK Depth 1] -> main() [Stack Base Frame] Initiating Transaction: $250 [CALL STACK Depth 2] -> processTransaction() [Child Activation Frame] Calculated Fee: $10 Net Total Dispatched: $260 [CALL STACK Depth 1] -> main() [Terminating Frame]
動作のしくみ: ステップ解説
- 4-5 行目: main() から呼び出す前に、関数シグネチャを GCC に伝えるプロトタイプを宣言します。
- 17 行目: processTransaction を呼び出し、スレッドスタックに新しいアクティベーションフレームを積みます。
- 27-34 行目: 呼び出し先フレームがローカルコピーを参照し、*outFee ポインタ経由で呼び出し元メモリを更新します。
- 33 行目: フレームがスタックからポップされ、正味合計が呼び出し元 main フレームへ返されます。
重要ポイント
- プロトタイプがないと C コンパイラは暗黙の int 宣言とみなし、現代の C99/C11 規格では警告やエラーになります。
- C の引数は厳密な値渡しであるため、メモリアドレス(&)を渡さない限り関数内での変更は呼び出し元に影響しません。
- 関数呼び出しごとに、引数・ローカル変数・戻り命令アドレスを含むアクティベーションレコードが積まれます。
- ポインタを渡すことで、グローバル変数を使わずに呼び出し元のスタックメモリへ結果を安全に書き戻せます。
よくある間違い: ローカルスタック変数へのポインタを返す
関数が終了してスタックフレームが破棄されるとローカル変数も消滅します。そのポインタを返すとダングリングポインタとなり未定義動作を引き起こします。
❌ 誤り
int* createCounter() { int count = 5; return &count; } // Undefined Behavior: count memory deallocated!✅ 正しい例
void initializeCounter(int* outCount) { *outCount = 5; } // Safe: mutates caller allocated memory関連するCチュートリアルとコンパイラ
C言語のポインタ:メモリアドレス、間接参照(*)、ポインタ演算
C言語のポインタ(アドレス取得 &、間接参照 *、疑似参照渡し、ポインタ演算)を習得しましょう。
C言語のファイル I/O:fopen、fread、fwrite、fclose
C標準の FILE* ハンドル、fopen、fclose を使ってディスクストリームを読み書きしましょう。
C言語のプリミティブデータ型と明示的な書式指定子
C言語の基本型(int, float, double, char, unsigned long)、sizeof によるメモリサイズ取得、printf の書式指定子を習得します。
C オンラインコンパイラ
Compilra IDE で開く