0

This is a testing code of my program:

#include <iostream>
#include "ctype.h"
using std::cout;

int main(){
    cout << "Welcome to the program: ";
    cout << "\n" << "Let's see if the value of \'x\' is digital: ";
    int x = 5;
    cout << isdigit(x);
    
    cout << "\n" << "Let's see if the value of \'i\' is alphabetical: ";
    char i = 'i';
    cout << isalpha(i);
    
    return 0;
}

The results:

Welcome to the program:

Let's see if the value of 'x' is digital: 0

Let's see if the value of 'i' is alphabetical: 2

Values like 2 or 0 while both of them are true? shouldn't it be just 0 or 1 values shown in the results? Note: I didn't change the values with 'enum' or '#define' in the global variable section.

Community
  • 1
  • 1

2 Answers2

6

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.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
2

No, isalpha and isdigit do not return a bool, nor are they required to return 1. They're specified to return a non-zero value if the predicate is satisfied, zero otherwise.