C语言:宏函数
不方便检查错误,但是方便维护,容易出错。
#include<iostream>
using namespace std;
//C->宏函数
// advantage:代码可维护性,宏函数提高效率,减少栈桢的建立
// disadvantage:可读性差,没有类型安全的检查,不方便调试
//宏函数,后面没有分号
#define ADD(a,b) ((a)+(b))
//多行宏函数应该注意换行符
#define SWAP(a,b)\
int temp = a;\
a = b;\
b = temp;
int main(void)
{
ADD(1, 2);
if (ADD(1, 2)) {};
ADD(1, 2) * 3;//外面括号运用场景
int x = 1, y = 2;
ADD(x | y, x & y);//里面括号运用场景
int a = 10, b = 20;
SWAP(a, b);
cout << a <<" " << b;
return 0;
}
C++ inline(感觉很像关键字register)
#include<iostream>
using namespace std;
//C++->inline 符合条件的情况下展开
//尽量用从const,enum,inline替代宏
// 建议类似(register),递归不适合或者函数内部实现代码很长
// 内联以空间换时间,编译出来的程序变大
//不能声明和定义声明
inline int Add(int a, int b)
{
printf("%d", a);
return a + b;
}
inline void func(int a, int b)
{
cout << a + b << endl;
cout << a + b << endl;
cout << a + b << endl;
cout << a + b << endl;
cout << a + b << endl;
cout << a + b << endl;
cout << a + b << endl;
}
int main(void)
{
func(1, 2);
Add(2, 3);
return 0;
}
但是我发现我的VS在debug状态下没有识别inline关键字,不过在release状态下可以