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\n",&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");
}

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

 

 纳尼~居然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\n",a);
}
void main()
{
    func1();
    func2();
    system("pause");
}

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

 

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

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

 

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-02-10
  • 2021-06-29
  • 2022-12-23
  • 2021-08-18
  • 2022-12-23
  • 2021-12-05
猜你喜欢
  • 2021-05-29
  • 2022-12-23
  • 2021-07-24
  • 2021-09-06
  • 2022-12-23
相关资源
相似解决方案