1.内联函数(inline)
#include <iostream>
using namespace std;
void inline fun(int a, int b); /* 每调用一次内联函数,就会将该函数复制一份,调用次数多的话,会比较占用内存空间,所以内联函数的代码量一般不大 */
// inline void fun(int a, int b); // 也可以
#define FUN(a,b) do{cout << a+b << endl;cout << a -b<< endl;} while(0) /* 用do...while(0)后,if(true)后面就可以不跟大括号 */
int main(int argc, const char * argv[])
{
fun(3+4, 5);
if(true)
FUN(3+5,6); // 使用宏定义也能实现内联函数的功能,但写起来比较复杂
return 0;
}
void fun(int a, int b)
{
cout << a + b << endl;
cout << a - b << endl;
}
2.可在编译时计算为常量的函数(constexpr)
#include <iostream>
using namespace std;
constexpr int fac(int n)
{
return (n > 1)?fac(n - 1)*n:1;
}
int main(int argc, const char * argv[]) {
// constexpr
/* 1. 带有constexpr关键字的函数不能定义函数原型,即:带constexpr关键字的函数必须定义在main前面 */
// 2. constexpr函数内部的语句必须可以转换为常量
int jc = fac(10); /* 因为fac已经使用了constexpr关键字,所以fac(10)在编译时就已经转换为了3628800,就相当于:int jc = 3628800 */
cout << jc << endl;
return 0;
}
#include <iostream>
using namespace std;
constexpr int fac(int n)
{
return (n > 1)?fac(n - 1)*n:1;
}
int main(int argc, const char * argv[]) {
int n = 10;
constexpr int jc = fac(10); /* 只有参数是值的时候才会转换,即fac(n)不会转换,前面加上了constexpr关键字,表示这句话必须被转换,即fac中的参数必须是值 */
int i = 1/0;
cout << jc << endl;
return 0;
}
3.引用类型的变量
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
int value1 = 100;
// 引用类型变量必须初始化,而且初始化的值不能是数值
int &value2 = value1; // 引用类型变量的定义
cout << "value1 = " << value1 << endl; // 100
cout << "value2 = " << value2 << endl; // 100
value2 = 300;
cout << "value1 = " << value1 << endl; // 300
cout << "value2 = " << value2 << endl; // 300
cout << "value2 address = " << &value2 << endl;
int *pvalue = &value2; // 指针,指向value1
cout << "*pvalue = " << *pvalue << endl; // 300
return 0;
}
4.引用类型的函数参数
#include <iostream>
using namespace std;
void fun1(int a, int b) // 普通类型的函数参数
{
a = a + b;
}
void fun2(int *a, int b) // 指针类型的函数参数
{
*a = *a + b; //