How to define multiple characters using macros??
I want to declare all the hexadecimal digits under a name "hexa". Does anyone know it how to do that??

The below code is wrong! Any suggestions to make it correct??

#define hexa 'A','B','C','D','E','F','0','1','2','3','4','5','6','7','8','9'
#include<stdio.h>
int main()
{
char a;
printf("Enter a character= ");
scanf("%c",a);
if(a==hexa)
  printf("hexadecimal");
return 0;   
}

Recommended Answers

All 3 Replies

The #define directive is a glorified cut and paste. You can see why that macro is wrong by doing the cut and paste manually:

if(a=='A','B','C','D','E','F','0','1','2','3','4','5','6','7','8','9')
    printf("hexadecimal");

Well, you may not see it because this is a common confusion point for beginners to C. You don't compare a variable to a list directly like this, you must compare the variable to each individual item. So to compare against 'A', 'B', 'C', 'D' (because it's shorter for this example), you'd do this:

if (a == 'A' || a == 'B' || a == 'C' || a == 'D')
    printf("A, B, C, or D\n");

Obviously that's tedious, so a better solution is to store the "list" of matches in an array and then loop over the array while doing that comparison:

#include<stdio.h>

int main(void)
{
    char const hex[] = "0123456789ABCDEF";
    char ch;

    printf("Enter a character: ");
    fflush(stdout);

    if (scanf("%c", &ch) == 1)
    {
        int i;

        for (i = 0; hex[i] != '\0'; ++i)
        {
            if (ch == hex[i])
            {
                printf("Hexadecimal\n");
                break;
            }
        }
    }

    return 0;   
}

The take-away lesson is that C doesn't do jack for you and there's very little "magic". You have to do everything explicitly, or use a library to do it for you explicitly.

Basicall you can't do what you are trying to do at line 8. You can not compare a value to an array of values, you have to do the comparison individually, or in this case have a string containing your hexadecimal characters and use a string search function (such as strchr) to see if your entered character is contained in that string.

Thanks for your replies!! :)
I got it!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.