0

Is there a C macro, a GCC directive or pragma, to consume the next code statement following the macro, without explicitly passing it as an argument to the macro?

Something like this:

#define CONSUME_NEXT_IF(a) if (a) { (<next>) } else; 

And I would use it as:

CONSUME_NEXT_IF(a) stmt1;

And expect it to expand to:

  if (a) stmt1; 
  else;

I am using an if statement here just as an example. The conditional statement isn't the point, rather the ability to consume stmt1 by the macro without actually passing it as an argument.

MEE
  • 2,114
  • 17
  • 21
  • 1
    `(a) &&` should do. – EOF Jul 22 '16 at 23:19
  • @EOF, can you elaborate please? – MEE Jul 22 '16 at 23:22
  • Mhh, actually it won't always work. You'd need to make sure `stmt1` is always parenthesized or doesn't contain any operator of lower precedence than `&&`. – EOF Jul 22 '16 at 23:26
  • Can you explain why - other than obfuscating code - you would seek to do this? – Peter Jul 22 '16 at 23:38
  • @Peter Mainly syntax sugar. We have a relatively huge code base, and want to achieve a similar effect to annotations, without extensively messing with the code. – MEE Jul 22 '16 at 23:42

1 Answers1

2
#define CONSUME_NEXT_IF(a) if (!(a)) {} else

will achieve the effect of only executing the "next statement" (between use of the macro and next ;) if a is true (or non-zero). If you have suitable constraints on what type of expression a is, you might be able to remove the () on (a).

Personally, although you've explained in comments that you want a similar effect to annotations, I consider this will introduce more maintenance concerns - including code obfuscation - than it alleviates. Particularly if it interacts with other macros being used in a or stmt1.

And, of course, it would be necessary to modify your "large code base" to use the macro.

This also leaves dead code in your executable - it doesn't stop code for stmt1 being emitted to the executable (unless a has a fixed compile-time value, and your compiler has capability to detect and optimise code in such circumstances). Therefore such a construct will mean you cannot satisfy requirements of several assurance standards that require prevention of dead code.

Peter
  • 35,646
  • 4
  • 32
  • 74
  • If you're that worried about code-golfing this, why not `#define CONSUME_NEXT_IF(a) if(!(a)); else` to save a few character, rather than risk operator precedence woes by removing parentheses? – EOF Jul 23 '16 at 01:14