Try to search your question here, if you can't find : Ask Any Question Now ?

C: Best way to hide if-statement in macro

HomeCategory: stackoverflowC: Best way to hide if-statement in macro
Avatarkundan asked 5 months ago

What is the best practice of hiding if-statement in #define?

  1. You can use if in define:
#define MY_MACRO(isTrue) if(isTrue) do()

My intuition says that this is bad approach. Could you give an example, why it’s so or why not? For example, anyone who use this can add else after macro.

  1. You can use ternary operator:
#define MY_MACRO(isTrue) (isTrue) ? do() : do_not()
#define MY_MACRO(isTrue) (isTrue) ? do() : (void)0

Here I understand, why it’s not good. For example, anyone can call your function do() with simple true || MY_MACRO(?)

  1. My current solution for this issue is do-while-false
#define MY_MACRO(isTrue) do { if(isTrue) do(); } while (false)

Is this actually the best approach? What bad can happen with this macro?

1 Answers
Best Answer
AvatarMikhail answered 5 months ago
Your Answer

6 + 8 =

Popular Tags

WP Facebook Auto Publish Powered By :