2

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) 

edited

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?

8
  • To me, the first form is the more general and also (just imo) the more readable. Commented Sep 24, 2011 at 13:30
  • 3
    Neither is good as macros IMO shouldn't do flow control. Commented Sep 24, 2011 at 13:31
  • 1
    @geek 24 questions asked, 0 votes cast. That's pretty poor participation. Have a read of the faq. Commented Sep 24, 2011 at 13:37
  • @David Heffernan: Where does it say in the faq that you should be voting? (As a side note, it is a fundamental right in every decent democracy that you are not forced to vote, which is a good thing!) Commented Sep 24, 2011 at 13:43
  • 1
    @user786653, I would moderate that statement. Macros that do flow control should at least reflect that fact in their name. Something like ON_ERROR_RETURN or so. Commented Sep 24, 2011 at 14:15

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

but if I have a LOT such pieces of the code, what may be better than this?
I think it's fine for a small DSL for reading a config file or running a state machine where code conciseness has higher importance and you can have the presupposition that whoever touches the code understands what those macros do.
Sure, I'm not saying that they must be avoided at all cost, I'm just saying that, as always, you have to consider the clarity/convenience tradeoff.
0

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.