一般常量存储与修改常量数据的值

/*

**test8.cpp : Defines the entry point for the console application.

**系统winXP SP3 32位.

**一般常量存储

*/


#include "stdafx.h"


int main(int argc, char* argv[])

{

    char a = 'a';

    char* b = "ba";

    b = "a";  //此时将指针b指向内存中字符串"a\0",详见备注1。

/****************

    char* b = "ba";

    *b = "a";//这里更改的是b指向内存中常量的值,故是错误的,详见备注2。

*****************/

    char c = a + 2;

    printf("b = %c\n",*b);//b = a

    printf("c = %c\n",c);

    return 0;

}



Tips1:注意字符串”a”与’a’的不相等,因为字符串是以\0结尾的,即字符串”a”是a和\0,而字符’a’就是单个字符a。

Tips2:常量只能引用,不能修改,故一般将其保存在符号表里,而不是数据存储区。而符号表是只读的,不可修改。存储在符号表里会使得程序运行效率变高。



/*

**test9.cpp : Defines the entry point for the console application.

**系统winXP SP3 32位.

**修改常量数据的值

*/


#include "stdafx.h"


int main(int argc, char* argv[])

{

    const long clNum = 1;

    long* pl = (long*)&clNum;

    *pl = 2;

    printf("*pl = %d\n",*pl);//2,指针指向的内容被修改,指向2所在的内存。

    printf("clNum = %d\n",clNum);//1,原常量clNum的值没有改变。

/****************

那如何才能将常量的内容修改呢?

*****************/

    class Integer{

        public:

        long Integer_lNum;

        Integer():Integer_lNum(1){} //构造函数 ,值为1

};

    const Integer Integer_iNum;

    printf("Integer_iNum.Integer_lNum = %d\n",Integer_iNum.Integer_lNum);//执行默认构造函数,值为1

    Integer* pInt = (Integer*)&Integer_iNum;

    pInt->Integer_lNum = 2;

    printf("pInt->Integer_lNum = %d\n",pInt->Integer_lNum); //2

    printf("Integer_iNum.Integer_lNum = %d\n",Integer_iNum.Integer_lNum); //2,修改成功,原因见备注3

    return 0;

}

Tips3:const是只执行编译时候的强制安全检查,标准c语言中,const符号常量默认外连接(分配存储空间),不能再一个程序单元中定义多个同名的const符号常量。而在标准c++中,const常量默认为内连接,在不同编译单元中会加上不同前置链接名称,因此每个编译单元编译时候会为其独立分配存储空间,即认为是不同的常量,连接时候会进行常量合并进以优化程序执行效率。

你可能感兴趣的:(一般常量存储与修改常量数据的值)