Dangers with unscoped multiline MACROS

59 Views Asked by At

Is there a way to protect this MACRO from unscoped if/for statements?

#define FOO(X, Y, ...) X->bar(_##Y->thatVar, __VA_ARGS__);\
post_op(X, Y)

The order of bar and post_op is important and the result of post_op is ignorable to the application

i.e.

if(true)
    auto z = FOO(a,b);
else //compile error
    abort();
1

There are 1 best solutions below

1
StoryTeller - Unslander Monica On BEST ANSWER

Just use a lambda to reaggregate your statements back into an expression. Use it wherever an expression may appear, to your heart's content. Even in an expression statement inside an if with no braces.

#define FOO(X, Y, ...) [&] { \ 
  auto ret = X->bar(_##Y->thatVar, __VA_ARGS__);\
  post_op(X, Y); \
  return ret; }()