This article learn from Ditai Software College Tangzuo Lin teacher of C ++ courses
Introducing: introducing C ++ inline function is to replace the C macro function block
Experiment 1: VS macro block inline
注意:在C++开发中首选内联函数定义代码块,而不是宏
Experiment 2: Forced inline
C language macro constant text keys only performed during the pretreatment Alternatively, as a side effect, and does not make any syntax checking, type checking. So in C ++ for the const keyword has been upgraded, the constants const defined has become a constant in the true sense, rather than read-only variable, so in C ++ if we want to use a macro constants, we can use const given direct constant to replace the macro constants. Further, we can set C macro block, it appears to be a function of, but not function, so using the macro block, often with side effects. Providing solutions in C ++, the macro block is replaced ----- inline function in C
When the C ++ compiler does not satisfy the request inline function, the inline function became normal function, there are also push, jumps, returns and other expenses.
Experiment 1: VS macro block inline
#include <stdio.h>
#define FUNC(a, b) ((a) < (b) ? (a) : (b))
inline int func(int a, int b)
{
return a < b ? a : b;
}
int main(int argc, char *argv[])
{
int a = 1;
int b = 3;
int c = FUNC(++a, b);
printf("a = %d\n", a);
printf("b = %d\n", b);
printf("c = %d\n", c);
return 0;
}
mhr@ubuntu:~/work/c++$ g++ 6-1.cpp
mhr@ubuntu:~/work/c++$ ./a.out
a = 3
b = 3
c = 3
mhr@ubuntu:~/work/c++$
#include <stdio.h>
#define FUNC(a, b) ((a) < (b) ? (a) : (b))
inline int func(int a, int b)
{
return a < b ? a : b;
}
int main(int argc, char *argv[])
{
int a = 1;
int b = 3;
int c = func(++a, b);
printf("a = %d\n", a);
printf("b = %d\n", b);
printf("c = %d\n", c);
return 0;
}
mhr@ubuntu:~/work/c++$ g++ 6-1.cpp
mhr@ubuntu:~/work/c++$ ./a.out
a = 2
b = 3
c = 2
mhr@ubuntu:~/work/c++$
attribute () relative to the g ++ compiler, keyword, rather than the standard c ++ syntax supported. But special g ++ compiler supports things.
Experiment 2: Forced inline
#include <stdio.h>
//__forceinline
__attribute__((always_inline))
inline
int add_inline(int n);
int main(int argc, char *argv[])
{
int r = add_inline(10);
printf(" r = %d\n", r);
return 0;
}
inline int add_inline(int n)
{
int ret = 0;
for(int i=0; i<n; i++)
{
ret += i;
}
return ret;
}
mhr@ubuntu:~/work/c++$ g++ 6-2.cpp
\mhr@ubuntu:~/work/c++$
mhr@ubuntu:~/work/c++$
mhr@ubuntu:~/work/c++$ ./a.out
r = 45
mhr@ubuntu:~/work/c++$
mhr@ubuntu:~/work/c++$