1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > #define与const定义常量的区别

#define与const定义常量的区别

时间:2018-07-09 17:14:35

相关推荐

#define与const定义常量的区别

首先,#define 宏定义,使用方法如下:

1 #define PI 3.141592 3 #define MAX(a,b) a>=b?a:b

const使用方法 const [常量类型] 符号常量名=表达式;,如果在定义时缺省“常量类型”,则默认为int类型。如下:

1 const double PI = 3.14159;2 const TEST = 2;

下边通过例子来说明两者之间的区别:

首先#define, T2的值病不是想象中的0而是10,因为宏展开时知识简单的替换,T2被展开为x+x-x+x,所以结果为10.

int x = 5;#define T1 x+x#define T2 T1-T1cout<<"T1="<<T1<<", T2="<<T2<<endl;输出:T1=10, T2=10

其次const,这种方式先计算T1,所以T2为0。

int x = 5;const T1 x+xconst T2 T1-T1cout<<"T1="<<T1<<", T2="<<T2<<endl;输出:T1=10, T2=0

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。