Terminator Terminator - 1 year ago 66
C Question

How do I write if conditions like these in a macro?

I'm quite new to macros.

I know how to use if condition using ternary operator.

How do I convert this into a



I try my luck with this but seems like it is wrong:

#define ifcount(i,j) ((i)==(j)? count=count+1\

This is the code i'm trying to convert

Answer Source

Using (abusing) macros to change the flow of the program is usually a bad idea, because the people that will read your code (yourself in a few years) may get surprised by unexpected jumps in the program flow.

That said, your problem has nothing to do with the ternary operator. Actually the ternary operator cannot contain a break in its right side, only expressions.

But macros are allmighty, so you can just do:

#define ifcount(i,j) if ((i)==(j)) { count=count+1; break; }

The main problem with this macro is that people will write a ; when using it, and it will break badly if it is used between another if /else pair, without braces:

if (...)
else // <--- syntax error because the previous ; breaks the if /else relation

The standard solution is to use the do/while(0) idiom:

#define do { ifcount(i,j) if ((i)==(j)) { count=count+1; break; } } while (0)

But that will not work because the break will break this inner while, not the one you want (credit to @abelenky) below.

The only other C statement that allows a compound statement and ends with a ; is this one:

#define ifcount(i,j) if ((i)==(j)) { count=count+1; break; } else

The problem is that if you forget to add the ; when using ifcount(i,j), instead of a compiler error you will get a silently compiling and surprisingly change in behavior.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download