c语言下const修饰的变量
1、c语言下const修饰的变量都有空间
2. c语言的const修饰的全局变量具有外部链接属性
07 const修饰的变量.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>const int a = 10;//常量区,一旦初始化,不能修改void test()
{//a = 100; //全局的const不能直接修改int *p = (int*)&a;//const int 不是 int*p = 100;//全局的const不能间接修改printf("%d\n", a);
}int main()
{const int b = 20;//b = 200;//局部的const修饰的变量不能直接修改int *p = (int *)&b;*p = 200;printf("%d\n",b);//使用别的文件的全局const修饰的变量需要声明extern const int c;printf("c=%d\n",c);system("pause");return EXIT_SUCCESS;
}
c_test.c
const int c = 20;
这里也就验证了****2. c语言的const修饰的全局变量具有外部链接属性
c++下const修饰的变量
这里是修改不了bb的值,是由于在编译器编译的阶段对我们写的代码进行了优化
如图所示
要想修改bb的值,就要加入一个关键字volatile
这里地址1是因为不进行优化,返回的是一个bool类型,真的就是1,假的就是0
c++语言的const修饰的变量有时有空间,有时没有空间(发生常量折叠,且没有对变量进行取址操作)
07 const修饰的变量.cpp
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;const int aa = 10;//c++下没有内存void test01()
{//发生了常量折叠cout << "aa=" << aa << endl;//在编译阶段,编译器:cout<<"aa="<<10<<endl;//禁止优化关键字 volatilevolatile const int bb = 20;//栈区int *p = (int *)&bb;//进行了取地址操作,所以有空间*p = 200;cout << "bb=" << bb << endl;//在编译阶段,cout << "bb=" << 20 << endl;cout << "*p=" << *p << endl;//200cout << "bb的地址为" << (int)&bb << endl;cout << "p的地址为" << (int)p << endl;
}int main()
{test01();//c++修饰的全局变量具有内部链接属性//extern const int c;//cout << "c=" << c << endl;system("pause");return EXIT_SUCCESS;
}
c++_const.cpp
//const int c = 30; 内部链接属性extern const int c = 30;//c++下加上extern就是外部链接属性
c++编译器不能优化的情况
1.不能优化自定义数据类型
2.如果用变量给const修饰的局部变量赋值,那么编译器就不能优化
3.编译器是在编译阶段来优化数据
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;void test01()
{int a = 10;const int b = 20;//如果用变量给const修饰二点变量赋值,那么编译器不会优化int *p = (int *)&b;*p = 100;cout << "b=" << b << endl;cout << "*p=" << *p << endl;
}void test02()
{int a = 10;const int b = a;int *p = (int *)&b;*p = 100;cout << "b=" << b << endl;cout << "*p=" << *p << endl;
}int main()
{test01();cout << "-------------------" << endl;test02();system("pause");return EXIT_SUCCESS;
}