C - macros use technique - do while(0);

it is not common when you see a lot of C language has something similar to the following defintion. 

 

 

#define macro_name(arg) do  { \
  // ... \
} while (0);

 

but why do we have this touble, why to guard against some innocent piece of code with the nugatory/inconsequential code as above?

 

let's see some example.  first  I defined several macros. 

 

/**
* file: macros.cpp
* description: demonstrate how to use macros, and some of the techniques. 
*/

#define hash(x) do { \
	int y = 0; \
	if ((x) > 0) y = ((x) << 1) + 1; \
	else y = ((-x) << 1) + 1; \
	y; \
} while (0);


#define hash2(x) {\
	int y = 0; \
	if ((x) > 0) y = ((x) << 1) + 1; \
	else y = ((-x) << 1) + 1; \
	y; \
}

#define hash3(x) \
	int y = 0; \
	if ((x) > 0) y = ((x) << 1) + 1; \
	else y = ((-x) << 1) + 1; \
	y; 

 

and the code to test it. 

 

	// so apparantly you cannot use the macro in some if/while condition statement.
	//if (hash(1) != 3) { 
	//	cout << "hash macros works" << endl;	
	//}

	// but this is ok , you can treat the hash(i) as a single line of function. 
	for (int i = 0; i < 10; i ++) hash(i);

	// this is also OK, because there is a local scope indicator, but that should only work in C++, because C does not have local scope inside a local function?
	for (int i = 0; i < 10; i ++) hash2(i);

	// this is NOT ok,  when the code is expanded, you will see errors
	//for (int i = 0; i < 10; i++) hash3(i);

 

as you cna see, that with the necessary do while statement, and with the help from compiler (because it can optimize the hopeless do while (0); and run the code within only once), you can treat the macros defined as a single line code - many expect it to be. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值