How to define a macro that checks if a given character is a vowel?

The following code fragment does not give a compilation error, but it does not give the expected result, although this can be done in a simple if-else way, but I wanted to do this with macros. Here cis a character variable.

#define VOWELS 'a' || 'e' || 'i' || 'o' || 'u' || 'A' || 'E' || 'I' || 'O' || '
if (c == VOWELS) {
   printf("vowel = %c\n", c);
}


+4
source share
2 answers

This is because everything except the leftmost value in the macro is VOWELSnot tested with c. The macro expands to:

c == 'a' || 'e' || ...

So, basically, since a non-zero expression is checked (i.e. the numerical value of the character 'e'), which is always evaluated as 1.

What should be a macro:

#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 just use:

if(VOWEL(c))
{
    ...
}
+7

if(c == 'a' || 'e' || 'i' || 'o' || 'u' || 'A' || 'E' || 'I' || 'O' || 'U')

c==a, e, . , TRUE.

 #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);
}   
+3

Source: https://habr.com/ru/post/1667411/


All Articles