Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define a macro that tests if a given character is a vowel?

Tags:

c

macros

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);
}


like image 954
CaptainDaVinci Avatar asked Dec 24 '22 21:12

CaptainDaVinci


1 Answers

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))
{
    ...
}
like image 78
Govind Parmar Avatar answered May 10 '23 22:05

Govind Parmar