#include <stdio.h>


int main()

{

    const int a = 1;

    const int b = 2;

    int array[a+b]={0};

    for(int i=0;i<(a+b);i++){

       printf("array[%d]=%d\n",i,array[i]);  

    }


    printf("press enter to coun...");

    getchar();

    return 0;

}

上面这段代码在c编译器中会报错,因为编译器无法确定只读变量a和b值,也无法确定数组的大小,而c++编译器会将a,b视为常量,编译通过。这样看来c++中的const视乎和宏差不多

c++中的const常量类比宏定义

   const int c=5    #define c 5

c++中const常量与宏定义不同

   const常量是由编译器处理的,提供类型检查和作用域检查

在如下中:

#include <stdio.h>

void f()

{

  #define a 3;

  const int b=4;

}


void g()

{

    printf("a=%d\n",a);

}


int main(){

    f();

    g();

    printf("press enter to ...");

    getchar();

    return 0;

}

如果只想a在函数f中使用,可以在f结束时,#undefa,但是这样还不如直接使用const int a