Why is the isalpha declaration giving me an error code

I'm trying to use the isalpha function from the <ctype.h> library. I have used other functions from other libraries in different files but I cant get isalpha to work. The error is:

test.c:9:21: error: expected ')'
    int isalpha(int c);
                ^

The code I'm working on:

// Function Declarations
int isalpha(int c);

int main(void) {
    char letter = get_char("Letter:");
    bool yesno = isalpha(letter);

    if (yesno == true) {
        printf("True\n");
    } else {
        printf("False\n");
    }
}

The Library is included in the header I just didn't know how to include the header here.

Thanks for the help

1 answer

  • answered 2020-05-22 12:52 chqrlie

    You should just include <ctype.h> and not redefine isalpha with an explicit prototype in your code. The reason you get an error is isalpha() is probably defined as a macro in <ctype.h> and this macro gets expanded as the compiler parses your prototype and the result of the expansion is a syntax error.

    Note also that isalpha() should not be called with an argument of type char because it has undefined behavior for negative values on platforms where char is signed by default. Cast char arguments as (unsigned char) to avoid this undefined behavior.

    Furthermore, the return value of isalpha is an int and the value 0 means false and any other value means true. Comparing isalpha(letter) == true is incorrect. Your code relies on the boolean conversion between int and bool, which is available since C99, but it is error prone to rely on this implicit conversion as this subtlety is probably beyond your skill level.

    Here is a modified version:

    #include <ctype.h>
    #include <stdio.h>
    #include <cs50.h>
    
    int main(void) {
        char letter = get_char("Letter:");
    
        if (isalpha((unsigned char)letter) {
            printf("True\n");
        } else {
            printf("False\n");
        }
        return 0;
    }