2

I used this macro:

#define ISALPHA(text[i]) ('a'<=a && a<= 'z')|| ('A'<=a && a<= 'Z')? ("alpha"):("not alpha")

It gives this error: [Error] "[" may not appear in macro parameter list. How to give an array value as a parameter in macros in C?

2
  • 2
    What is wrong with using the library function isalpha? In any case text[i] should be in the macro invocation, not its definition. #define ISALPHA(a) ... Commented Jul 1, 2017 at 0:08
  • 1
    How to pass an array is not the problem here, since that is not what you are doing. You a testing a single character. Commented Jul 1, 2017 at 6:19

2 Answers 2

4

There are multiple bugs in your code, but the answer to the headline question is that you use a plain name in the macro argument list:

#define ISALPHA(c) ((('a' <= (c) && (c) <= 'z') || \
                     ('A' <= (c) && (c) <= 'Z')) ? "alpha" : "not alpha")

You then invoke the macro on array elements using:

ISALPHA(text[i])

Note the extensive use of parentheses in the macro to avoid problems with odd-ball macro arguments.

Much better than all that testing, though, would be to use the standard (locale-sensitive) isalpha() macro from <ctype.h>:

#define ISALPHA(c) (isalpha(c) ? "alpha" : "not alpha")

Bugs in your version include:

  • Using text[i] instead of a in the macro arguments.
  • Not enclosing uses of a in parentheses.
  • Not enclosing the whole macro in parentheses.
  • (Minor) The test for whether a character is alphabetic is inaccurate for some code sets, such as EBCDIC used on IBM mainframes.

Enclosing the strings in parentheses was unnecessary, but was not going to cause any trouble.

My choice to use c as a mnemonic for 'character' is stylistic or personal preference; using a consistently (for 'alphabetic', presumably) would be fine too.

Sign up to request clarification or add additional context in comments.

1 Comment

I'd suggest the biggest bug is the act of defining and using a macro at all ... it is completely unnecessary since the language provides safer features to achieve the same effect.
0

Why don't you use isalpha declared in ctype.h. It's much more safer than using macros. Don't get me wrong, macros are fine tools, provided that you know what you are doing but often enough you can end up with undefined behaviour and you don't realize it.

I've seen things like this (in 3rd party libraries)

#define min(x,y) ((x)<(y)?(x):(y))

that seems OK, but it's not. Later when you don't think what you are doing, you could do something like this:

int something(int x, int y)
{
    return min(x++, y);
}

which expands to

int something(int x, int y)
{
    return ((x++)<(y)?(x++):(y));
}

and yields undefined behaviour.

1 Comment

this is a question in a exam paper of the c module of my degree so i need to use macro specifically :-(

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.