Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a ternary operator in a define as oppose to using an if?

Tags:

c++

c

syntax

Suppose I have a macro defined, and I am using that macro within an if else statement

#include <iostream>

#define LOG(x) {if (x) std::cout << "What is up" << std::endl;}

int main(void) {
  if (true)
    LOG(true);
  else
    false;
  return 0;
}

Now this is a tricky case, I realized that depending on the indentation there might be some ambiguity about which 'if' the 'else' should go with.

I have came up with this soultion

(some_condition) ? dosomething() : true;

This solves the problem, but I am not sure what the repercussion of having a true statement are. Is this a good solution, or is there a better approach?

EDIT: Here is the code that I used, it doesn't work. See if you can fix this?

like image 751
Anonymous Avatar asked Aug 08 '13 15:08

Anonymous


1 Answers

Indentation is for the benefit of humans are makes no difference to the compiler. When in doubt, add braces, which I recommend you do all the time.

Macros are (usually) bad. Is there any reason you can't use a function?

If the result of (..?..:..) isn't "used" or "stored" anywhere, the result is just ignored, but the function will still be called. So your code should work fine, although it's bad and confusing style.

Unlike the other answers, I didn't notice the lack of braces in the macro would break the else. But it doesn't matter to me because I'd never use that macro for just that reason!

like image 178
Neil Kirk Avatar answered Nov 05 '22 18:11

Neil Kirk