-8

Following is the code:

#include<stdio.h>

int main()
{
    int alpha = 0, input;

    while((input = getchar() != EOF))
    {
        if(isalpha(input))
            alpha++;
    }

    printf("Num of alpha is %d", alpha);
    return(0);
}

I'm getting error as

isalpha was not declared in this scope

when compiled on DevC++ compiler.

  • 6
    Please try to find some documentation about the `isalpha` function. It will tell you that you need to `#include` a specific header file. – Some programmer dude May 12 '21 at 07:49
  • The parameter to `isalpha()` is supposed to be cast to `unsigned char` prior to calling the function (`isalpha( (unsigned char)input )`). Not doing so can get you in trouble on some machines where `char` is signed. – DevSolar May 12 '21 at 07:59
  • @DevSolar Is that cast really necessary? – klutt May 12 '21 at 08:02
  • @klutt Indeed I was mistaking this for a different usecase, when the argument is `char` or `signed char`. No, it is nit strictly necessaty here. But it is a good habit to get into, as the errors from not doing so can be hard to catch. – DevSolar May 12 '21 at 11:13
  • @DevSolar Personally, I would say that casting when it's not necessary is a very bad habit, since that easily can hide errors. But if you restrict it to the isxxxx family I agree. – klutt May 12 '21 at 11:55
  • @klutt Yes, I meant it strictly for the is...() / to...() family of functions. – DevSolar May 12 '21 at 16:40

1 Answers1

0

isalpha() is declared in ctype.h

It might be good to know that even though the argument to isalpha (and all the isxxx family functions) is an int, the behavior is undefined if the argument is negative. So if you're on a machine where char is signed as default, you might run into trouble unless you cast first. Like this:

char c;
// Some code
if(isalpha((unsigned char) c)) {

It can be a good habit to always cast for these functions. However, do NOT use casting as a goto for silencing warnings. It can easily hide errors. In most cases when a cast is needed, your code is wrong in some other way. Rant about casting

Another pitfall with these functions (and many other C functions that returns an int as a Boolean) is that they are required to return zero on false, but are allowed to return any non-zero value on true. So a check like this is complete nonsense:

if( isalpha(c) == 1 ) 

Instead do any of these:

if( isalpha(c) != 0 )   // If not zero
if( isalpha(c) )        // Use directly as Boolean (recommended)
if( !! isalpha(c) == 1) // Double negation turns non zero to 1
klutt
  • 30,332
  • 17
  • 55
  • 95