Reputation: 1065
The following, code snippet does not give compilation error, but it does not give the expected output either, though this could be done in simple if-else way but I wanted to do it using macros. Here c
is a character variable.
#define VOWELS 'a' || 'e' || 'i' || 'o' || 'u' || 'A' || 'E' || 'I' || 'O' || '
if (c == VOWELS) {
printf("vowel = %c\n", c);
}
Upvotes: 4
Views: 501
Reputation: 8614
This will expand to
if(c == 'a' || 'e' || 'i' || 'o' || 'u' || 'A' || 'E' || 'I' || 'O' || 'U')
Which will check for c==a
and then logical OR it with e
which has a non zero value. So the result will always be TRUE.
What you want is
#define VOWELCHECK(c) ((c)=='a') || ((c)=='e') || ((c)=='i') || \
((c)=='o') || ((c)=='u') || ((c)=='A') || \
((c)=='E') || ((c)=='I') || ((c)=='O') || ((c)=='U')))
// In the program
if (VOWELCHECK(c))
{
printf("vowel = %c\n", c);
}
Upvotes: 3
Reputation: 21562
That's because everything but the leftmost value in the VOWELS
macro is not being tested against c
. What the macro expands to is:
c == 'a' || 'e' || ...
So basically, since a non-zero expression (i.e., the numeric value of the character 'e'
) is being tested for, that always evaluates to 1
.
What the macro should be is:
#define VOWEL(c) ((c) == 'a') || ((c) == 'e') || ((c) == 'i') || ((c) == 'o') || ((c) == 'u') || ((c) == 'A') || ((c) == 'E') || ((c) == 'I') || ((c) == 'O') || ((c) == 'U')
And then, you would simply use:
if(VOWEL(c))
{
...
}
Upvotes: 7