1. 内联函数:(C++)
inline int square1(int x){return (x)*(x);};
2. 宏:(C)
#define square2(x) (x)*(x);
例一:
int main(int argc, char* argv[])
{
int x = 2;
int ret = square1(x);
printf("x = %d, the square1 = %d/n", x, ret);
int y = 2;
ret = square2(y);
printf("y = %d, the square2 = %d/n", y, ret);
return 0;
}
执行结果:
x = 2, the square1 = 4
y = 2, the square2 = 4
例二:
int main(int argc, char* argv[])
{
int x = 2;
int ret = square1(x++);
printf("x = %d, the square1 = %d/n", x, ret);
int y = 2;
ret = square2(y++);
printf("y = %d, the square2 = %d/n", y, ret);
return 0;
}
执行结果:
x = 3, the square1 = 4
y = 4, the square2 = 4
例三:
int main(int argc, char* argv[])
{
int x = 2;
int ret = square1(++x);
printf("x = %d, the square1 = %d/n", x, ret);
int y = 2;
ret = square2(++y);
printf("y = %d, the square2 = %d/n", y, ret);
return 0;
}
执行结果:
x = 3, the square1 = 9
y = 4, the square2 = 16
为何会出现上面不同的结果呢?这就是内联函数和宏的最大区别之一。
内联函数和常规函数一样,是按值来传递参数的。
宏并不是通过传递参数来实现的,而是通过文本替换来实现的。本例中,宏中定义的x是“参数”的符号标记。
x = 2;
square2(x) = 2*2 = 4;
square2(x++) = (x++)*(x++) = 4;
square2(++x) = (++x)*(++x) = 16;
通过以上例子也可以得出一个结论:如果使用C语言的宏执行了类似函数的功能,那么在C++中应考虑将他们转化为C++的内联函数。