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言語】C言語基本① 関数宣言 関数のプロトタイプ【低レイヤー】

Last updated at Posted at 2024-11-09

低レイヤー層の勉強のためにC言語の学習を始めたので、他言語との違いなど基本的な仕様をメモ。
今回は関数の宣言。何かご指摘あれば是非お願いいたします。

ポイント 関数宣言とプロトタイプ

まず前提として、Cでは関数を呼び出す場合、宣言済みの関数しか実行できない。
その為、以下の2通りの方法で宣言する。

① 呼び出す箇所より前(main関数の上など)で宣言しておく。

#include <stdio.h>

// 関数の宣言
int sum(int a, int b){
    return a + b;
}

int main(void){
    // 使用部分
    int ans = sum(10, 11);
    
    printf("%d", ans);

    return 0;
}

②プログラムの冒頭に関数の概要=プロトタイプを宣言しておき、その後関数の詳細な定義をする。

#include <stdio.h>

//関数のプロトタイプ
int sum(int, int); // 引数は(int a, int b)等でも可

int main(void){

    // 使用部分
    int ans = sum(10, 11); 
    
    printf("%d", ans);
    return 0;
}

// 関数の詳細な定義
int sum (int a, int b){
    return a + b;
}


それぞれのメリット・デメリット
①プロトタイプ省略
   ○ プロトタイプを書かなくてよいので記述量が少ない。
   × 関数から別の関数を呼び出す場合、その宣言の順番を気をつけないといけない。
     (※ただし言語規格のバージョンやコンパイラによる模様。C99だとエラー?)

②プロトタイプ記述
   ○ 関数関数の宣言の順番を気にせず記述できる。
   × 記述量が増える。

シンプルなコードの場合は①で良いのかも知れませんが、基本的には②の方がよさそうです。

その他詳細・今後の学習課題

参考文献・サイト

0
0
5

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?