The isXXX()
functions will return an integer representing a true or false value. Given that zero is false and anything else is true, two is a perfectly acceptable return value.
The reason you're getting a false value for isdigit(5)
is because that function takes a character and tells you whether it's a digit. While '5'
may be a digit character, 5
is most likely not.
C++ defers to C for these functions since they're part of the cctype
header. The relevant portion of the standard (C99 7.4
) states:
The header <ctype.h>
declares several functions useful for classifying and mapping characters. In all cases the argument is an int
, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF
.
The functions in this subclause return nonzero (true) if and only if the value of the argument c
conforms to that in the description of the function.
Generally, in C, and in C++ C-legacy functions (a), you should never be comparing a truth value against a fixed true/false value. Since it treats zero as false, everything else as true, the correct way to do it would be something like:
cout << "It " << (isdigit(x) ? "is" : "isn't") << " a digit";
(a) This is usually a good rule to follow, even for C++ bool
comparisons (and other languages) where it has to be true or false.
If a boolean value or function is properly named (and it should be), the right way to do it is:
if (! errorOccurred) ...
if (isComplete) ...
if (isdigit(myChar)) ...
That's because, using reductio ad absurdum, the expression boolVal == TRUE
is simply another boolean value, so where do you stop?
if (isComplete == TRUE) ...
if ((isComplete == TRUE) == TRUE) ...
if (((isComplete == TRUE) == TRUE) == TRUE) ...
if ((((isComplete == TRUE) == TRUE) == TRUE) == TRUE)...
And so on, ad infinitum.