c++对c的扩展----什么时候分配内存

const分配内存的时机,编译器编译的时候分配内存

const相当于宏,用来取代c语言的#define

#include<iostream>
using namespace std;
void main()
{
    int a = 20;
    const int b = 30;
    const int d = 40;
    int c = 40;
    //int array[a+c] linux gcc编译器支持
    //int array[b+d] linux gcc编译器支持
    printf("变量a,b,c的地址分别为%d %d %d
",&a,&b,&c);
    system("pause");
}

作用域和变量类型检测

#include<iostream>
using namespace std;
void func1()
{
    #define a 5
    const int b = 22;
    string name = "陈培昌";
    int age = 22;
}
void func2()
{
    printf("a的值是%d",a);
}
void main()
{
    func1();
    func2();
    system("pause");
}

 纳尼~居然func2能访问func1中的常量!!!,如果我们禁止这类访问可以这样

#include<iostream>
using namespace std;
void func1()
{
    #define a 5
    const int b = 22;
    string name = "陈培昌";
    int age = 22;
    #undef a
}
void func2()
{
    printf("a的值是%d
",a);
}
void main()
{
    func1();
    func2();
    system("pause");
}

 然而const类型则无法访问,说明const是严格限制作用域范围的

原文地址:https://www.cnblogs.com/saintdingspage/p/11937009.html