C++ inline,const,static
1 inline
在曾经的版本里有一种写法
#define sum(a,b) a+b
那么我们就可以完成如下操作
#pragma once
#ifndef __FL_A
#define __FL_A
#include <iostream>
#include <cstdio>
#define plus(a,b) a+b
using namespace std;
int a = 1;
int b = 2;
int main(){
int c = plus(a,b); // a+b
cout << c << endl;
return 0;
}
#endif
如上,这种定义最大的好处在于 凑代码量 方便(手动狗头),同时可以让一些运算快速一些执行。
那么,相应的,inline的出现基本取代并优化了原来的用法;这种前缀可以使运算在CPU中快速进行,提高程序的速度。
有人就说了:给所有函数都加个inline前缀不是可以提高速度吗?何乐而不为?
那么就很遗憾,比如说下面的程序:
#pragma once
#ifndef __FL_B
#define __FL_B
#include <iostream>
#include <cstdio>
using namespace std;
inline int function(int n){
int s1 = 10,s2 = 100;
int* sp = &s2;
int* sp2 = &s1;
for (int i=0;i<n;++i){
for (int j=0;j<i;++j){
if (i&1 || j&1){
(*sp2) += n%(*sp);
}
}
}
// 此处省略infinity行
return s2 - s1;
}
int main(){
int c = plus(a,b); // a+b
cout << c << endl;
return 0;
}
#endif
没错,对于递归循环等复杂的函数,inline不能起到它的效果。
2 const
const就比较简单了,表示常量,即不能修改的量。
相信不少人通过修改地址等一系列的魔幻操作修改了常量的值;
不过吧const这个东西既然定义了就真没什么太大的修改必要。
const可以用在数组的大小定义上。
#include <iostream>
using namespace std;
const int N = 1007;
int arr[N][N]; //较大数组最好定义在main函数外
int main(){
...
return 0;
}
3 static
static是静态变量。
在本文件内通过static定义的变量,不能被其他文件访问。
例:ex1.cpp
#include <iostream>
using namespace std;
static int a = 100;
int b = 100;
void fun(){
cout << a << endl;
cout << b << endl;
}
假如在这个文件的main函数内调用fun(),输出的则是100(换行)100.即a,b都能成功访问。
但如果现在多了一个ex2.cpp:
#include <iostream>
#include "ex1.cpp"
using namespace std;
void fun(){
cout << a << endl;
cout << b << endl;
}
那么此时a就不能被访问了。
因此,对于一些开发项目的程序员而言,将仅用于此文件的变量声明static是一种代码规范。
同时,static有一个非常牛的特性,即它可以在函数内被定义,但是能够起到近乎全局变量的作用。
例:
#include <iostream>
using namespace std;
void fun(){
int sch = 0;
}
int main(){
fun();
cout << sch << endl;
return 0;
}
以上代码不能通过编译,因为sch是局部变量。
但以下就可以了:
#include <iostream>
using namespace std;
void fun(){
static int sch = 0;
}
int main(){
fun();
cout << sch << endl;
return 0;
}
因此说static可以加强程序的模块化。
今天的文章水到这里到这里就结束了,感谢阅读~
--------------------------- 谁都有底线,文章也不例外🐼 -------------------------------------------