06_関数
プロトタイプ宣言
- C言語ではコンパイラがファイルの上からコンパイルするため、関数を使用する際に先に宣言を行う必要がある。
- プロトタイプ宣言が不要な言語に関しては、先に全体を解析してからコンパイルを行うため、プロトタイプ宣言が不要。
#include
宣言で宣言されている以外の自作関数を呼び出す際はプロトタイプ宣言で宣言する。
サンプルプログラム
#include <stdio.h>
#include <stdlib.h>
/*プロトタイプ宣言*/
int addStatic(int addValue);
int add(int addValue);
void showValue(int showValue);
int main()
{
int repeatCount = 0;
printf("動的な変数の場合\n");
for (repeatCount = 0; repeatCount < 4; repeatCount++){
showValue(add(repeatCount));
}
printf("静的な変数の場合\n");
for (repeatCount = 0; repeatCount < 4; repeatCount++){
showValue(addStatic(repeatCount));
}
system("pause");
return 0;
}
int add(int addValue)
{
int sum=0;
sum += addValue;
return sum;
}
int addStatic(int addValue)
{
static int sum;
sum += addValue;
return sum;
}
void showValue(int showValue)
{
printf("値は%d\n", showValue);
}
出力結果
動的な変数の場合
値は0
値は1
値は2
値は3
静的な変数の場合
値は0
値は1
値は3
値は6
続行するには何かキーを押してください . . .
関数の再帰呼び出し
サンプルプログラム
#include <stdio.h>
#include <stdlib.h>
/*プロトタイプ宣言*/
int factorial(int);
int main()
{
int count;
for (count = 1; count < 11; count++){
printf("%d! = %d \n",count,factorial(count));
}
system("pause");
return 0;
}
int factorial(int value)
{
if (value == 0){
return 1;
}
else {
return value * factorial(value - 1);
}
}
出力結果
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
続行するには何かキーを押してください . . .
int factorial(int value){
return (value == 0) ? 1 : value * factorial(value-1);
}