Originally Posted by
psppb
I am trying to write a macro that returns true if its parameter is divisible by ten. False if otherwise.
Macros don't actually return anything. They just get replaced by some code.
So, let's examine the code:
Code:
#define modulus(x) {if(x%10 == 0){printf("true\n"); else printf("false\n");}}
If we expand the replacement code out nicely:
Code:
{
if(x%10 == 0){
printf("true\n");
else printf("false\n");
}
}
Now, it is clear that the else does not match the if because of the misplaced braces. What you should do is either write out the replacement code first and then compress it into one line, or use backslashes at the end of the line as line continuations so you can write:
Code:
#define modulus(x) do { \
if (x % 10 == 0) { \
printf("true\n"); \
} else { \
printf("false\n"); \
} \
} while (0)
I've used a do while(0) so that a missing terminating semi-colon would result in an error, whereas just using braces for a code block will not, which can look weird sometimes.