0

Is it correct way to write a multiple statements in one Macro?

 #define AB() do { printf("hi"); } while(0)
msc
  • 33,420
  • 29
  • 119
  • 214

2 Answers2

1

Yes.

Although the correct way is most often to not have any function-like macro at all.

Please note that the do-while(0) trick is only relevant in code bases with sloppy brace style, such as

if(x)
  AB();
else

The do-while(0) trick will prevent compiler errors caused by the stray semi-colon, if there is an else statement following. Had the macro only used braces, you'd get if(){}; else which is a syntax error.

Note that the above brace style caused one of the most expensive software bugs in history, known as the Apple "goto-fail" bug. So there are very sound reasons never to use it. If you always use {} after every statement, the do-while(0) trick also turns irrelevant.

Lundin
  • 195,001
  • 40
  • 254
  • 396
0

Yes this is the correct way.

Ideally you want a macro to expand into a single statement, not a compound statement. Yours satisfies that.

You can safely use this macro in an if, else block.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483