what is the better way to use macro and why 1)
CHECK(foo());
#define CHECK(foo) do{ \
UCHAR status = foo; \
if(0 != status) \
// do some stuff \
return status; \
}while(0)
or 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.
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()
. Option 1 also keeps the scope of the status
variable as small as possible. Option 2 leaks the status variable into the scope of the caller.
Option 3 which doesn't use a macro at all is even better!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.