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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With