C++笔记 第三课 进化后的const分析---狄泰学院

版权声明:原创·禁止转载 https://blog.csdn.net/weixin_42187898/article/details/83116692

如果在阅读过程中发现有错误,望评论指正,希望大家一起学习,一起进步。
学习C++编译环境:Linux

第三课 进化后的const分析

1.C语言中的const

const修饰的变量是只读的,本质还是变量
const修饰的局部变量在栈上分配空间
const修饰的全局变量在只读存储区分配空间
const只在编译期有用,在运行期无用
const修饰的变量不是真的常量,它只是告诉编译期该变量不能出现在赋值符号的左边。
C语言中的const使得变量具有只有只读属性
const将具有全局生命周期的变量存储于只读存储区
const不能定义真正意义上的常量!enum可以,枚举

3-1.cpp C/C++中的const

#include <stdio.h>
int main()
{
    const int c = 0;
    int* p = (int*)&c;
    
    printf("Begin...\n");
    *p = 5;
    
    printf("c = %d\n", c);
    printf("*p = %d\n", *p);
    
    printf("End...\n");
    
    return 0;
}
test.c中结果
lkk@lkk-virtual-machine:~/c++$ gcc test.c
lkk@lkk-virtual-machine:~/c++$ ./a.out
Begin...
c = 5
*p = 5
End...
3-1.cpp中结果
lkk@lkk-virtual-machine:~/c++$ g++ 3-1.cpp
lkk@lkk-virtual-machine:~/c++$ ./a.out
Begin...
c = 0
*p = 5
End...

2.C++中的const

C++在C的基础上对const进行了进化处理
当碰到const声明时在符号表中放入常量
编译过程中若发现使用常量则直接以符号表中的值替换
编译过程中若发现下述情况则给对应的常量分配存储空间
对const常量使用了extern
对const常量使用&操作符
注:C++编译器虽然可能为const常量分配空间,但不会使用其存储空间中的值。

C语言中的const变量
C语言中的const变量是只读变量,会分配存储空间
C++中的const常量(由只读变量成真正的常量)
可能分配存储空间
当const常量为全局,并且需要在其它文件中使用
当使用&操作符对const常量取地址
C++中的const常量类似于宏定义
const int c = 5; ≈#define c 5
C++中的const常量在与宏定义不同
const常量是由编译器处理
编译器对const常量进行类型检查和作用域检查
宏定义由预处理器处理,单纯的文本替换

3-2.cpp const与宏

#include <stdio.h>
void f()
{
    #define a 3
    const int b = 4;
}
void g()
{
    printf("a = %d\n", a); //cpp看到的为printf("a = %d\n", 3);
    //printf("b = %d\n", b); //cpp报错,没有在当前作用域起作用
}
int main()
{
    const int A = 1;
    const int B = 2;
    int array[A + B] = {0};
    int i = 0;
    
    for(i=0; i<(A + B); i++)
    {
        printf("array[%d] = %d\n", i, array[i]);
    }
    
    f();
    g();
    
    return 0;
}
test.c中结果
lkk@lkk-virtual-machine:~/c++$ gcc test.c
test.c: In function ‘main’:
test.c:19:5: error: variable-sized object may not be initialized
     int array[A + B] = {0};
     ^
test.c:19:25: warning: excess elements in array initializer
     int array[A + B] = {0};
                         ^
test.c:19:25: note: (near initialization for ‘array’)
3-1.cpp中结果
lkk@lkk-virtual-machine:~/c++$ g++ 3-2.cpp
lkk@lkk-virtual-machine:~/c++$ ./a.out
array[0] = 0
array[1] = 0
array[2] = 0
a = 3
End...

小结

与C语言不同,C++中的const不是只读变量
C++中的const是一个真正意义上的常量
C++编译器可能会为const常量分配空间
C++完全兼容C语言中const常量的语法特性

猜你喜欢

转载自blog.csdn.net/weixin_42187898/article/details/83116692