Reputation: 43
Why am I getting the answer "odd" instead of "even"?
#include<stdio.h>
#define ODD(x) x%2?0:1
int main()
{
int a=5;
if(ODD(a+1))
printf("even");
else
printf("odd");
return 0;
}
Upvotes: 1
Views: 119
Reputation: 153407
ODD(a+1)
expands to a+1%2?0:1
. With a
as 5, that is same as (5+(1%2))?0:1
or 0.
%
beats +
which beats ?:
if(0)
printf("even");
else
printf("odd"); // print `odd`
Perhaps you wanted some ()
to insure evaluation order.
// #define ODD(x) x%2?0:1
#define ODD(x) ((x)%2?0:1)
Yet that seems backwards. How about
#define ISODD(x) ((x)%2 != 0)
See How do I check if an integer is even or odd?
Upvotes: 3
Reputation: 67476
I do not like this kind if macros for many reasons (one of it that they can be a source of silly errors - like in your case). It should be domain of functions.
int ODD(int x)
{
return x & 1;
}
if you are worried about function call overhead just make it inline (but on any level op optimisation the compiler will inline it anyway as the call is probably longer than the function itself.
Upvotes: 1
Reputation: 881363
#define ODD(x) x % 2 ? 0 : 1
Given an even number x
, x % 2
will give you zero, which is false.
Hence the result of the entire ternary expression will be the second option 1
, which is true.
You would be better off with something like:
#define ODD(x) (((x) % 2) != 0)
It's both more readable in intent, and less prone to errors such as getting the true/false values mixed up, or being burnt by simple text substitution having unexpected effects.
Upvotes: 1
Reputation: 279
1 is treated as true and 0 as false.
if (1)
is executed always, and when you get 0
as result, the branch shifts to else
so code should be :
if ODD is true (returning 1 from terneray expression), print "odd"
Upvotes: 3