const
:const
修饰的变量是只读的,本质仍是变量const
修饰的局部变量在栈上分配空间const
修饰的全局变量在只读存储区分配空间const
只在编译期有用,在运行期无效const
不能定义真正意义上的常量const
修饰的变量不是真的常量,它只是告诉编译器该变量不能出如今赋值符号的左边。const
局部变量是在栈上分配空间,能够经过指针改变这个空间里面的值。过了编译期,const
变量的常量特性,只读特性就没有了,只读特性只在编译期有效,运行期根本无效。const
修饰的全局变量在只读存储区分配空间,所以若是用指针去修改了const
修饰的全局变量,程序就会崩溃,由于修改了程序只读存储区中内容,大部分程序都会发生崩溃。ios
const
:C++在C的基础上对const
进行了进化处理,具体表如今:c++
const
声明时,在符号表中放入常量编译过程当中也可能为对应的常量分配存储空间:数组
const
用在全局或者使用了static
关键字说明,存放在只读数据区数据结构
extern const int i = 10; static const int i = 10; // 或者修饰全局变量 const int a =10; int main() {}
const
常量使用了&
操做符,在栈区分配空间注意:C++编译器虽然可能为const
常量分配空间,但不会使用其存储空间中的值符号表是编译过程当中产生的一种数据结构函数
#include <iostream> #include <string> using namespace std; const int i = 10; // 若是经过指针去改变i,就会出现段错误:尝试修改只读数据区数据 int main() { const int a = 5; int *p = (int *)&a; // &a, 给a标识符分配空间了,并用p指向了该空间, // 能够经过*p访问这个地址,可是不能经过a来访问 *p = 10; // 不能经过指针去改变a的值 cout << a << endl; cout << *p << endl; return 0; }
C++ 中的const
常量相似于宏定义spa
const int c = 5; // 相似于 #define c 5
可是cosnt
与宏定义的区别在于:指针
const
常量是有编译器处理cosnt
常量进行类型检查和做用域检查#include <stdio.h> void f() { #define a 3 const int b = 4; } void g() { printf("a = %d\n", a); // 在g函数中访问f函数中的宏定义,彻底没有问题 // 在预处理的时候就进行了宏替换,对编译器来讲,就是printf("a = %d\n", 3); // 宏是没有做用域的概念 // const 定义的常量,被编译器处理,是有做用域的,不能访问b printf("b = %d\n", b); } int main() { const int A = 1; const int B = 2; int array[A + B] = {0}; /* C编译 const修饰获得的只是具备只读特性的变量,数组的大小是由两个变量的大小决定的, 两个变量相加的结果须要在运行的时候才能直到,所以编译器编译的时候不知道这个数组长度,直接报错 */ /* C++编译 const是定义的真正意义上的常量,直接从符号表中取值,编译的时候就知道A和B的值, 能够获得数组的长度,不会报错 */ int i = 0; for(i=0; i<(A + B); i++) { printf("array[%d] = %d\n", i, array[i]); } f(); g(); return 0; }