C++中#define和const的区别

一、#define是预处理指令(pre-processor directive)而const是关键字

#define用于给一些值定义名称(字符串),这样定义的字符串在C、C++中称为宏定义,而const是一个关键字(keyword)或用于使标识符(identifier)的值为常量

众所周知, 从 C++ 源代码可执行文件要经历4个过程

  1. 预处理:对源代码文件中的文件包含关系(头文件)预编译语句(宏定义)进行分析和替换。
  2. 编译
  3. 汇编
  4. 链接

#define是在第一步 “预处理”的时候执行的。const不是。

二、#define无作用域限制而const有

Macro)可以被定义在当前程序的任意位置或者被当前程序包含(include)的头文件中,因此宏无作用域限制。但是 常量(constant)被定义在函数中,因此常量只能在它被定义的函数的作用域中才能被访问
使用 const总是一个好习惯。因为使用 const 我们可以控制它的作用域。如果它被放在任意用户自定义函数中,那么它只能在该函数中起作用。

#include <iostream>
using namespace std;

//macro definition
#define X 30

//global integer constantt
const int Y = 10;

int main()
{
	//local ineteger constant`
	const  int Z = 30;
	
	cout<<"Value of X:  "<<X<<endl;
	cout<<"Value of Y:  "<<Y<<endl;
	cout<<"Value of Z:  "<<Z<<endl;  

	return 0;
}

输出

Value of X: 30 
Value of Y: 10 
Value of Z: 30

在上面的程序中,X全局符号常量(global symbolic constant),在编译前经过预处理Y 也是全局常量,而 Zmain函数 的局部常量

三、宏(#define)可以重定义但是const不能

宏(已定义,defined)可以在程序中的任何位置重新定义(通过先取消定义然后定义,un-defining and then defineing)。但是常量不能被 重定义,我们甚至不能对常量再次赋值(re-assign)。

#include <iostream>
using namespace std;

//macro definition
#define X 30

int main()
{
	cout<<"Value of X: "<<X<<endl;
	#undef X
	#define X 300
	cout<<"Value of X: "<<X<<endl;

	return 0;
}

输出:

Value of X: 30
Value of X: 300

我们成功改变了 X 的值。

#include <iostream>
using namespace std;

//constant int 
const int Y=10;

int main()
{
	cout<<"Value of Y: "<<Y<<endl;
	Y=100;	//error, we can not assign value to const
	cout<<"Value of Y: "<<Y<<endl;

	return 0;
}

输出:

main.cpp: In function 'int main()': 
main.cpp:10:3: error: assignment of read-only variable 'Y'  
  Y=100; //error, we can not assign value to const  
   ^

我们可以看到,在我们尝试改变 Y (一个常量)的值的时候,报了一个编译错误(compilation error)。

注:全文翻译自Difference between const and #define in C, C++ programming language,局部有增删改动。

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值