常量折叠 Constant folding

常量折叠:在编译时期用常量的具体取值代替所有用到常量的地方。
例如
const int a = 8;
cout << a << endl;
经过编译器扫描后,变为:
cout << 8 << endl;

常量一般分为两种:可以常量折叠的常量和不可以常量折叠的常量。下面具个不可以常量折叠的常量的例子:
int test(){ return 8; }
const int a = test();//常量a不可以常量折叠
cout << a << endl;//由于a不可以常量折叠,所以经过编译器扫描之后仍然是“cout << a << endl;”

 

编译器会为常量分配了地址,但是在使用常量的时候,常量会被一立即数替换(保护常量,防止被破坏性修改)

在C++中对于基本类型的常量,编绎器并不为其分配存储空间,编译器会把它放到符号表,当取符号常量的地址等操作时,将强迫编译器为这些常量分配存储空间,编译器会重新在内存中创建一个它的拷贝,通过地址访问到的就是这个拷贝而非原始的符号常量

#include 

using namespace std;

int test(){
    return 10;
}
int main()
{
    const int a=test();//不可常量折叠
     const int a=10;//可常量折叠
    int *p = const_cast(&a);
    *p=5;
    cout<<&(a)<<" "<


不可常量折叠情况输出:

0x28fef8 0x28fef8
5  5

 


可常量折叠情况输出:

0x28fef8 0x28fef8
10  5

 

你可能感兴趣的:(C++)