Reputation:
I am trying to write macro IS_ALPHABETIC
that gives a non-zero value if a character is an alphabetic character. In it I am referring to a IS_LOWER_CASE
macro I defined and the uppercase
macro I defined earlier.
Here is what I have:
#include <stdio.h>
#define uppercase(n) ((n) <= 'Z' && (n) >= ('A') )
#define IS_LOWER_CASE(n) ( ((n) >= 'a') && ((n) <= 'z') )
#define IS_ALPHABETIC(n) (uppercase(n) || IS_LOWER_CASE(n) ? (n) : 5)
int main()
{
char letter = "4";
printf("%d\n", IS_ALPHABETIC(letter));
}
So essentially the IS_ALPHABETIC
macro is supposed to give the value 5 if the argument is an alphabetic character because it checks it if is a lowercase or uppercase alphabetic character, however it gives 5 each time regardless of the argument.
For example, in my case, I entered 4 so it shouldn't give the value 5. It should only when I enter an alphabetic value.
The uppercase
and IS_LOWER_CASE
macros just check whether the argument is uppercase or lowercase, respectively.
I am not 100% sure if I constructed my IS_ALPHABETIC
macro correctly. What is wrong?
I am trying to do it strictly using these specific macros.
Upvotes: 0
Views: 3386
Reputation: 126
#include <stdio.h>
#define IS_UPPER_CASE(n) (((n) <= 'Z') && ((n) >= 'A'))
#define IS_LOWER_CASE(n) (((n) >= 'a') && ((n) <= 'z'))
#define IS_ALPHABETIC(n) (IS_UPPER_CASE(n) || IS_LOWER_CASE(n) ? (n) : 5)
int main()
{
char letter = 'a';
printf("%d\n", IS_ALPHABETIC(letter));
}
Above is the edited version of your code snippet and it will not return 5 all the times.
char letter = "4";
The above initialization generates a compiler warning as you are trying to initialize a char with an address (of the string "4" and not character 4).
However, for your inputs you might want to print the character if it is an alphabet. But what is going to be printed is the integer value equivalent to the ASCII value of the character. So, you might try %c instead of %d in the printf() call.
Upvotes: 0
Reputation: 213200
Change:
char letter= "4";
to:
char letter= '4';
Also turn on compiler warnings (e.g. gcc -Wall ...
) - let the compiler catch silly mistakes like this for you and save yourself a lot of time and effort.
Note that you probably want IS_ALPHABETIC
to return TRUE/FALSE (1/0) instead of n or 5.
And on a matter of programming style, try to be more consistent with naming, formatting, use of parentheses, etc, e.g. here is a cleaned up version of your code:
#include <stdio.h>
#define IS_UPPER_CASE(n) ((n) >= 'A' && (n) <= 'Z')
#define IS_LOWER_CASE(n) ((n) >= 'a' && (n) <= 'z')
#define IS_ALPHABETIC(n) (IS_UPPER_CASE(n) || IS_LOWER_CASE(n))
int main()
{
char letter = '4';
printf("%d\n", IS_ALPHABETIC(letter));
return 0;
}
Upvotes: 10