関数定義の例

以下の例には、int へのポインターとして宣言された table と、int 型として宣言された length が指定されている関数宣言子、i_sort が入っています。 パラメーターとしての配列を、暗黙的にエレメント型へのポインターに変換することに注意してください。

/**
 ** This example illustrates function definitions.
 ** Note that arrays as parameters are implicitly
 ** converted to a pointer to the type.
 **/
 
#include <stdio.h>
 
void i_sort(int table[ ], int length);
 
int main(void)
{
   int table[ ]={1,5,8,4};
   int length=4;
   printf("length is %d¥n",length);
   i_sort(table,length);
}
void i_sort(int table[ ], int length)
{
  int i, j, temp;
 
  for (i = 0; i < length -1; i++)
    for (j = i + 1; j < length; j++)
      if (table[i] > table[j])
      {
        temp = table[i];
        table[i] = table[j];
        table[j] = temp;
      }
}

次の例は、関数宣言 (また、関数プロトタイプ とも呼ばれます) の例です。

double square(float x);
int area(int x,int y);
static char *search(char);

次の例は、関数宣言子で typedef ID を使用する方法を示しています。

typedef struct tm_fmt { int minutes;
                      int hours;
                      char am_pm;
                    } struct_t;
long time_seconds(struct_t arrival)

次の関数 set_date は、date 型の構造体へのポインターをパラメーターとして宣言します。 date_ptr は、ストレージ・クラス指定子 register を持っています。

void set_date(register struct date *date_ptr)
{
  date_ptr->mon = 12;
  date_ptr->day = 25;
  date_ptr->year = 87;
}

C

C99 では、宣言内のパラメーターごとに少なくとも 1 つの型指定子が必要です。 これにより、暗黙の int が宣言されているかのようにコンパイラーが振る舞う状況の数が少なくなります。

C99 より前は、foo の宣言内の b または c の型があいまいであり、コンパイラーは両方に対して暗黙の int を想定しました。

int foo( char a, b, c )
{
   /* statements */
}

関連参照

IBM Copyright 2003