関数プロトタイプ typedef は関数定義で使用できますか? 質問する

関数プロトタイプ typedef は関数定義で使用できますか? 質問する

同じプロトタイプを持つ一連の関数があるとします。

int func1(int a, int b) {
  // ...
}
int func2(int a, int b) {
  // ...
}
// ...

ここで、定義と宣言を簡素化したいと思います。もちろん、次のようなマクロを使用することもできます。

#define SP_FUNC(name) int name(int a, int b)

しかし、私はそれを C のままにしておきたいので、これにはストレージ指定子を使用しようとしましたtypedef

typedef int SpFunc(int a, int b);

これは宣言には問題なく機能するようです:

SpFunc func1; // compiles

ただし、定義についてはそうではありません。

SpFunc func1 {
  // ...
}

次のようなエラーが発生します。

error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token

これを正しく行う方法はありますか、それとも不可能ですか? 私の C の理解では、これは機能するはずですが、機能しません。なぜですか?


gccは私が何をしようとしているのか理解しています。なぜなら、次のように書くと、

SpFunc func1 = { /* ... */ }

それは私に教えてくれる

error: function 'func1' is initialized like a variable

つまり、gcc は SpFunc が関数型であることを理解します。

ベストアンサー1

関数型の typedef を使用して関数を定義することはできません。これは明示的に禁止されています - 6.9.1/2 および関連する脚注を参照してください。

関数定義で宣言された識別子(関数の名前)は、関数定義の宣言子部分で指定された関数型を持つ必要があります。

関数定義の型カテゴリは typedef から継承できないことが意図されています。

typedef int F(void); // type F is "function with no parameters
                     // returning int"
F f, g; // f and g both have type compatible with F
F f { /* ... */ } // WRONG: syntax/constraint error
F g() { /* ... */ } // WRONG: declares that g returns a function
int f(void) { /* ... */ } // RIGHT: f has type compatible with F
int g() { /* ... */ } // RIGHT: g has type compatible with F
F *e(void) { /* ... */ } // e returns a pointer to a function
F *((e))(void) { /* ... */ } // same: parentheses irrelevant
int (*fp)(void); // fp points to a function that has type F
F *Fp; //Fp points to a function that has type F

おすすめ記事