2
4

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 3 years have passed since last update.

C言語 インライン関数

Last updated at Posted at 2020-11-06

インライン展開

関数にはインライン展開を指定することができます。
inlineが指定されている関数は、「インライン関数」と呼ばれ、コンパイラーは「インライン展開」を行う場合があります。

関数呼び出しコードをその場に展開する「インライン展開」

インライン展開は、関数呼び出しのコードをその場に展開する機能です。
コンパイラーは関数呼び出しのコストをなくすことができるので、コードを読みやすくしたまま、生成されるプログラムの実行速度を上げることができます。

マクロとインライン関数の違い

翻訳フェーズ - cppreference.com

マクロ関数の定義と展開はフェーズ4、インライン関数の展開はフェーズ7で行われます。

マクロ関数の展開は、概念的にテキストとしての(最高でも字句レベルでの)切り貼り操作に近いものになります。それにより、たとえば展開結果のかっこの対応のチェックや識別子のスコープチェックなどはマクロの段階では行なえません。

インライン関数の解釈や展開は、構文解析後に、言語構文を壊すことなく、つまり展開後の小0度が構文エラーをこすことなく、構文の型やチェックの元で行われます。

FreeBSDでの実装例

stand.h
/* min/max (undocumented) */
static __inline int imax(int a, int b) { return (a > b ? a : b); }
static __inline int imin(int a, int b) { return (a < b ? a : b); }
static __inline long lmax(long a, long b) { return (a > b ? a : b); }
static __inline long lmin(long a, long b) { return (a < b ? a : b); }
static __inline u_int max(u_int a, u_int b) { return (a > b ? a : b); }
static __inline u_int min(u_int a, u_int b) { return (a < b ? a : b); }
static __inline quad_t qmax(quad_t a, quad_t b) { return (a > b ? a : b); }
static __inline quad_t qmin(quad_t a, quad_t b) { return (a < b ? a : b); }
static __inline u_long ulmax(u_long a, u_long b) { return (a > b ? a : b); }
static __inline u_long ulmin(u_long a, u_long b) { return (a < b ? a : b); }

参考

C初心者が知っておきたいヘッダーファイルとリンクの基礎知識 (3/4):目指せ! Cプログラマ(終) - @IT

C言語でマクロ関数とインライン関数の違いはなんですか? - Quora

2
4
0

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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?