David Stocking
David Stocking

Reputation: 1210

isalpha(<mychar>) == true evaluates to false?

string temp is equal to "ZERO:\t.WORD\t1" from my debugger. (the first line of my file)

string temp = RemoveWhiteSpace(data);
int i = 0;
if ( temp.length() > 0 && isalpha(temp[0]) )
    cout << "without true worked" << endl;
if ( temp.length() > 0 && isalpha(temp[0]) == true )
    cout << "with true worked" << endl;

This is my code to check if first character of temp is a a-z,A-Z. The first if statement will evaluate to true and the 2nd to false. WHY?!?!?! I have tried this even without the "temp.length() > 0 &&" and it still evaluates false. It just hates the "== true". The only thing I can think of is that isalpha() returns != 0 and true == 1. Then, you could get isalpha() == 2 != 1. But, I have no idea if C++ is that ... weird.

BTW, I dont need to know that the "== true" is logically pointless. I know.

output was

without true worked

Compiled with CodeBlock using GNU GCC on Ubuntu 9.10 (if this matters any)

Upvotes: 5

Views: 3624

Answers (4)

osgx
osgx

Reputation: 94455

Do not isalpha(ch) == true, but !!isalpha(ch) == true

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490623

The is* functions are only guaranteed to return a non-zero value if true, NOT necessarily a 1. A typical implementation is table based, with one entry in the table for each character value, and a set of bits defining which bit means what. The is* function will just AND the right bitmask with the table value, and return that, which will only be the value 1 for whichever type happens to have been given bit position 0.

E.g.:

#define __digit 1
#define __lower 2
#define __upper 4
extern int __type_table[];

int isdigit(int c) { 
    return __type_table[c+1] & __digit;
}

int isalpha(int c) { 
    return __type_table[c+1] & (__lower | __upper);
}

int islower(int c) { 
    return __type_table[c+1] & __lower;
}

int isupper(int c) { 
    return __type_table[c+1] & __upper;
}

Where __type_table is defined as something like int __type_table[UINT_MAX+1]; and would be initialized so (for example) __type_table['0'+1] == __digit and __type_table['A'+1] == __upper.

In case you care, the '+1' part is to leave a spot at the beginning of the table for EOF (which is typically defined as -1).

Upvotes: 9

Ben Voigt
Ben Voigt

Reputation: 283823

Well, the documentation suggests that it returns either zero or non-zero, not necessarily just false or true. So you'd better check (isalpha(temp[0]) != 0).

Upvotes: 0

avakar
avakar

Reputation: 32685

isalpha doesn't return true, it returns non-zero. This is quite common for API designed for C.

Note that in the expression isalpha(ch) == true, the subexpression true is promoted to type int with value 1.

Upvotes: 2

Related Questions