良好的编程习惯在C宏定义(#定义) [英] Good Programming Practices for Macro Definitions (#define) in C

查看:116
本文介绍了良好的编程习惯在C宏定义(#定义)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,从来没有定义一个宏是这样的:

For example, never define a macro like this:

#define DANGER 60 + 2

这有可能是危险的,当我们做一个操作是这样的:

This can potentially be dangerous when we do an operation like this:

int wrong_value = DANGER * 2; // Expecting 124

相反,像这样定义,因为你不知道怎么宏的用户可以使用它:

Instead, define like this because you don't know how the user of the macro may use it:

#define HARMLESS (60 + 2)

这个例子是微不足道的,但pretty多解释了我的问题。是否有任何一套准则或最佳实践编写宏时,你会建议?

The example is trivial, but that pretty much explains my question. Are there any set of guidelines or best practices that you would recommend when writing a macro?

感谢您的时间!

推荐答案

你不仅应该把括号围绕参数,你应该把周围的前pression括号回来了。

Not only should you put parens around the arguments, you should put parens around the expression returned.

#define MIN(a,b)  a < b ? a : b     // WRONG  

int i = MIN(1,2); // works
int i = MIN(1,1+1); // breaks

#define MIN(a,b)  (a) < (b) ? (a) : (b)   // STILL WRONG

int i = MIN(1,2); // works
int i = MIN(1,1+1); // now works
int i = MIN(1,2) + 1; // breaks

#define MIN(a,b)  ((a) < (b) ? (a) : (b))   // GOOD

int i = MIN(1,2); // works
int i = MIN(1,1+1); // now works
int i = MIN(1,2) + 1; // works

然而, MIN(3,我++)仍然是断开...

最好的规则的只使用#定义只有在没有其他办法将工作!我知道你问关于C而不是C ++,但还是记住了他。

The best rule is only to use #defines only when NO OTHER APPROACH WILL WORK! I know you're asking about C instead of C++, but still bear his in mind.

这篇关于良好的编程习惯在C宏定义(#定义)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆