LoginSignup
0
0

More than 1 year has passed since last update.

【C】初めてのC言語(9. 関数のプロトタイプ宣言)

Posted at

はじめに

学習環境

  • 今回はpaiza.ioのC言語のエディタを使いました。

これまでに感じていた疑問

  • 【C】初めてのC言語(5. 関数)で学習していた時、以下のようにmain関数の下にtestという名前の関数を作って、main関数内からtest関数を呼び出すとコンパイルエラーが発生しました。
    • そこで試しにtest関数をmain関数よりも上に持ってくると、無事にコンパイルが通りました。
  • このように「ある関数を呼び出す時は、その関数を定義した箇所より後ろでないとコンパイルが通らない」というのはさすがに変だと思いましたが、この時は解決策が分からずに「main関数を先頭に持ってくる」という対応で済ませてしまいました。
main.c
#include <stdio.h>

int main(void){
    test();
    return 0;
}

void test(void) {
    printf("This is test.");
}
コンパイルエラーの内容
Main.c:4:5: warning: implicit declaration of function 'test' is invalid in C99 [-Wimplicit-function-declaration]
    test();
    ^
Main.c:8:6: error: conflicting types for 'test'
void test(void) {
     ^
Main.c:4:5: note: previous implicit declaration is here
    test();
    ^
1 warning and 1 error generated.

プロトタイプ宣言

  • 上記のように関数を定義する順番を縛られるのではなく、自由に関数を定義するには「プロトタイプ宣言」という構文を利用します。
プロトタイプ宣言の構文
{戻り値のデータ型} 関数名({引数1}, {引数2}, ...);

サンプルコード

  • 上記のコンパイルエラーとなったコードと似ていますが、プロトタイプ宣言をすることで正常にコンパイルすることができました。
    • void test(void);の箇所がプロトタイプ宣言です。
main.c
#include <stdio.h>

// 関数のプロトタイプ宣言
void test(void);

int main(void){
    test();
    return 0;
}

// test関数の呼び出し箇所より後ろでtest関数を宣言できる!
void test(void) {
    printf("This is test.");
}

参考URL

参考資料

0
0
2

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