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
kundan asked 2 weeks 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
Mikhail answered 2 weeks ago
Your Answer

2 + 19 =

Popular Tags

WP Facebook Auto Publish Powered By :