答え
![](/wp-content/include/images/avatar/teacher/14.png)
この書き方だと引数が「不定」になってしまう!
void SayHello();
![](/wp-content/include/images/avatar/teacher/13.png)
引数が「ない」ときは、こう書くのが正解!
void SayHello(void);
解説
今回のプログラムは、第06問と似ていますね。サブルーチンSayHello()
を手前で宣言して、main()
から呼び出せるようにしています。ただし、SayHello()
には引数がありません。
こういう場合、引数リストを省略して()
と書くと、C言語では引数が「不定」という扱いになってしまいます。引数が「ない」ときは、そのことを(void)
と明示しなければなりません。
そのため、SayHello()
の宣言は、正しくはこう書きます。
void SayHello(void);
定義するときも同様で、こうです。
void SayHello(void) {
……
}
さらに、main()
も同様です。
int main(void) {
……
}
![](/wp-content/include/images/avatar/student/5.png)
質問でーす!引数が「不定」の関数って、どういうときに使うんですか?
![](/wp-content/include/images/avatar/teacher/10.png)
それがねぇ、使わないのよ。
![](/wp-content/include/images/avatar/student/11.png)
ええっ!
![](/wp-content/include/images/avatar/teacher/2.png)
引数が「不定」っていうのはね、古いバージョンのコンパイラの仕様なの。
![](/wp-content/include/images/avatar/student/7.png)
昔の書き方ってことですか?
![](/wp-content/include/images/avatar/teacher/3.png)
そうそう。古いプログラムが動かなくなってしまわないように、昔の書き方も許されているということね。
なおC++では、引数リストを()
と省略すると、(void)
と同じように引数「なし」の意味になります。C言語よりも新しいプログラミング言語なので、歴史的な「しがらみ」も少ないというわけです。
ここがポイント!
![](/wp-content/include/images/avatar/teacher/6.png)
引数「なし」の関数は
(void)
と書こう!
修正後のプログラム
main.c
#include <stdio.h>
#include <stdlib.h>
void SayHello(void);
int main(void) {
SayHello();
return EXIT_SUCCESS;
}
void SayHello(void) {
puts("Hello!");
}
実行結果
Hello!