11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

かわった関数プロトタイプ宣言

Last updated at Posted at 2014-11-18

C/C++系の「関数型」の変な使い方。
typedef int F(int, int)よりはusing F = int(int, int)の方がマシ。

関数ポインタならtypedef int (*PF)(int, int)またはusing PF = int(*)(int, int)となる。

sample.c
# include <stdio.h>

/* 2個のint型引数をとってint型を返す関数型 F を宣言 */
typedef int F(int, int);

/* F型の関数 add, sub の宣言 */
F add, sub;

int main()
{
  int x = 1, y = 2;
  /* 関数 add, sub の呼び出し */
  int r1 = add(x, y);
  int r2 = sub(x, y);
  printf("add(%d,%d)=%d\n", x, y, r1); /* 3 */
  printf("sub(%d,%d)=%d\n", x, y, r2); /* -1 */
}

/* 関数 add, sub の定義 */
int add(int x, int y) { return x + y; }
int sub(int x, int y) { return x - y; }
sample.cpp
# include <cstdio>

// 2個のint型引数をとってint型を返す関数型 F を宣言
// (C++11で導入されたalias declaration構文)
using F = int(int, int);

// F型の関数 add, sub の宣言
F add, sub;

int main()
{
  int x = 1, y = 2;
  // 関数 add, sub の呼び出し
  int r1 = add(x, y);
  int r2 = sub(x, y);
  std::printf("add(%d,%d)=%d\n", x, y, r1); // 3
  std::printf("sub(%d,%d)=%d\n", x, y, r2); // -1
}

// 関数 add, sub の定義
int add(int x, int y) { return x + y; }
int sub(int x, int y) { return x - y; }
11
11
1

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
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?