geek
geek

Reputation: 2847

good macro practice in c

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?

Upvotes: 2

Views: 241

Answers (2)

Matteo Italia
Matteo Italia

Reputation: 126937

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.

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 613511

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!

Upvotes: 0

Related Questions