#include <stdio.h>
inline int square(int x) {
return x * x;
}
int main() {
int num = 5;
printf("Square of %d is %d\n", num, square(num));
return 0;
}
解説:
inlineキーワードを使用して関数を宣言します。
関数の展開により、関数呼び出しのコストが削減されます。
2. インライン関数の利点
パフォーマンス向上:関数呼び出しのオーバーヘッドがなくなるため、高速化が期待できます。
コードの可読性向上:関数を使用して処理を整理しつつ、高速な実行が可能です。
最適化の柔軟性:コンパイラがインライン展開を判断するため、効率的なコード生成が行われます。
3. インライン関数の使用例
3.1 計算処理を効率化
例:2つの数の最大値を求めるインライン関数
#include <stdio.h>
inline int max(int a, int b) {
return (a > b) ? a : b;
}
int main() {
int x = 10, y = 20;
printf("Max of %d and %d is %d\n", x, y, max(x, y));
return 0;
}
#include <stdio.h>
inline double min(double a, double b) {
return (a < b) ? a : b;
}
int main() {
double x = 3.14, y = 2.71;
printf("Min of %.2f and %.2f is %.2f\n", x, y, min(x, y));
return 0;
}