0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

c言語の基本を解説⑤

0
Last updated at Posted at 2026-08-26

C言語における関数(Function)は、特定の処理をまとめて1つのブロックにしたものです。

プログラムを機能ごとに分割することで、コードの読みやすさ(可読性)や再利用性、保守性が大幅に向上します。

1. 関数の基本構造

関数は主に「戻り値の型」「関数名」「引数(ひきすう)」「本体」の4つの要素で構成されます。

戻り値の型 関数名(引数の型 引数名) {
    // 処理内容
    return 戻り値;
}

基本的な関数の例

2つの数を足し算して結果を返す関数の例です。

#include <stdio.h>

// 関数の定義
int add(int a, int b) {
    int sum = a + b;
    return sum; // 呼び出し元に結果を返す
}

int main() {
    // 関数の呼び出し
    int result = add(5, 3);
    printf("結果: %d\n", result); // 結果: 8
    return 0;
}

2. 関数の重要用語

  • 引数(ひきすう / Parameter / Argument):
    関数を呼び出す際に、外部から渡すデータのこと。

  • 戻り値(返り値 / Return Value):
    関数の中の処理が終わったあと、呼び出し元に返す結果データのこと。return ステートメントで指定します。

  • void 型:
    「何も返さない」または「引数を取らない」ことを明示する特殊な型です。

// 引数も戻り値もない関数
void printHello(void) {
    printf("Hello, World!\n");
    // return は不要(書いてもよい)
}

3. 値渡しとポインタ渡し(重要概念)

C言語の引数の渡し方には大きな違いを生む2つの方法があります。

① 値渡し (Call by Value)

引数の値のコピーが関数に渡されます。関数内で値を変更しても、呼び出し元の変数は変化しません。

void update(int x) {
    x = 100; // コピーを変更しているだけ
}

int main() {
    int n = 10;
    update(n);
    printf("%d\n", n); // 10 のまま(変化なし)
}

② ポインタ渡し (参照渡しと同等の効果)

変数のアドレス(メモリ上の位置)を渡すことで、呼び出し元の変数を関数の中から直接書き換えることができます。

void updateByPointer(int *p) {
    *p = 100; // アドレス先(元の変数)を書き換える
}

int main() {
    int n = 10;
    updateByPointer(&n); // アドレスを渡す
}

4. プロトタイプ宣言

C言語では、原則として使用する前に関数が定義されている必要があります。main 関数の後ろに関数を書きたい場合は、プログラムの先頭で「プロトタイプ宣言」を行います。

#include <stdio.h>

// プロトタイプ宣言(関数の存在をあらかじめ伝える)
int multiply(int x, int y);

int main() {
    int val = multiply(4, 5); // エラーにならない
    printf("%d\n", val); // 20
    return 0;
}

// 関数の本体
int multiply(int x, int y) {
    return x * y;
}

まとめ

  • 定義の基本: 戻り値の型 関数名(引数) { 処理 return 戻り値; }
  • 何も返さない場合: 戻り値の型に void を使う
  • 変数を書き換えたい場合: アドレスを渡す「ポインタ渡し」を利用する
  • 順序の注意: 関数を main より下に書く場合は「プロトタイプ宣言」が必要
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?