[英]good macro practice in c
what is the better way to use macro and why 1) 什么是使用宏的更好方法,为什么1)
CHECK(foo());
#define CHECK(foo) do{ \
UCHAR status = foo; \
if(0 != status) \
// do some stuff \
return status; \
}while(0)
or 2) 或2)
UCHAR status = foo();
CHECK(status);
#define CHECK(status) do{ \
if(0 != status) \
// do some stuff \
return status; \
}while(0)
thank You for all of You guys, a lot of people say that it is not good to use such piece of the code, but I have a lot of such pieces in my code (which I didn't write, only modify), what can You suggest? 感谢你们所有人,很多人说使用这样的代码段不好,但是我的代码中有很多这样的段(我没有写,只是修改了),你可以建议吗?
I'd say the first one, since it takes care of avoiding multiple evaluation of foo
, and who uses it doesn't need to remember to create the extra variable. 我要说第一个,因为它避免了对
foo
多次求值,并且使用它的人不需要记住要创建额外的变量。
Still, personally I don't like macros that alter the execution flow like that, a programmer first seeing the codebase can easily miss a return point of the function. 尽管如此,我个人还是不喜欢这样的宏来改变执行流,程序员首先看到的是代码库,很容易错过函数的返回点。
Option 1 is easier to use since there is no need for the caller to worry about multiple evaluations of foo()
. 选项1更易于使用,因为调用者无需担心
foo()
多次求值。 Option 1 also keeps the scope of the status
variable as small as possible. 选项1还使
status
变量的范围尽可能小。 Option 2 leaks the status variable into the scope of the caller. 选项2将状态变量泄漏到调用方的范围内。
Option 3 which doesn't use a macro at all is even better! 根本不使用宏的选项3更好!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.