宏定义 #define 和常量 const

2017-09-04  本文已影响0人  有毒工作室

定义常量

宏定义 #define 和常量 const 的区别

void f1 ()
{
    #define N 12
    const int n 12;
}
void f2 ()
{
    cout<<N <<endl; //正确,N已经定义过,不受定义域限制
    cout<<n <<endl; //错误,n定义域只在f1函数中
}
void f1()
{
  #define N 12
  const int n = 12;

  #undef N //取消宏定义后,即使在f1函数中,N也无效了
  #define N 21//取消后可以重新定义
}
const int A=10;       //正确。
const int A;          //错误,没有赋初始值。
extern const int A;   //正确,使用extern的外部变量。
上一篇 下一篇

猜你喜欢

热点阅读