0

I was running into an issue with my program for Vigenere's Cipher and singled it out to a problem with the equivalence of the value that is returned from isalpha() and the boolean "true".

I now know that this is poor syntax, but why does the following code not evaluate to true and print "Hello!"?

if (isalpha('A') == true)
    {
        printf("Hello!\n");
    }
2

The problem is a lack of understanding of how many of these functions work. While you would think that isalpha() would return a bool, it doesn't. Instead, it returns a number. If it is false, it returns 0, but if true, it returns a non-zero number. The problem is that the numeric value of "TRUE" is not necessarily the same as the number that is returned by isalpha().

Want to see what's going on? Try the following:

printf("isalpha() returns %i for true.\n", isalpha('A') );

My memory is not what it used to be, but I believe that, historically, this whole family of functions returned a power of 2. Which power of two would depend on which function it was. I believe that this was related to calculations that required register math, so that the bit that was turned on would indicate which function had returned the value. But I could be wrong. ;-)

In any case, the standard is that 0 is always equal to false, but any non-zero (positive or negative) represents true. So, to get to the point of your problem, just simplify the code to if (isalpha('A')) and it will work.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Thank you so much, Cliff. Excellent explanation! – jos0909 Jan 18 '17 at 5:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .