Why does isdigit() return 2048 if true?
Asked Answered
O

2

7

Can anybody explain why does isdigit return 2048 if true? I am new to ctype.h library.

#include <stdio.h>
#include <ctype.h>
int main() {
  char c = '9';
  printf ("%d", isdigit(c));
  return 0;
}
Opportuna answered 30/6, 2013 at 15:20 Comment(5)
Because "C" doesn't have a "bool" type, but it has the concept of a boolean, such that "0" is "false" and everything else is "true", and 2048 != 0 so it is true.Fluid
C does have a bool type. More precisely, it has a built-in boolean type named _Bool, and a macro definition #define bool _Bool in the standard header <stdbool.h>. But that was added by the 1999 ISO C standard, and isdigit() predates it.Absonant
BTW: On other systems one may get a non-zero value other than 2048.Pictish
Just as an aside. If you really want true/false to be 1 or 0 just use the !! work-around: printf("%d", !!isdigit(c));Afraid
possible duplicate of isalpha(<mychar>) == true evaluates to false?Beller
E
24

Because it's allowed to. The C99 standard says only this about isdigit, isalpha, etc:

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.

As to why that's happening in practice, I'm not sure. At a guess, it's using a lookup table shared with all the is* functions, and masking out all but a particular bit position. e.g.:

static const int table[256] = { ... };

// ... etc ...
int isalpha(char c) { return table[c] & 1024; }
int isdigit(char c) { return table[c] & 2048; }
// ... etc ...
Edict answered 30/6, 2013 at 15:22 Comment(3)
It is probably returning a bit field. 2048 has only one bit set. OP could check if other is functions also return a single bit set.Jere
I don't know if this is the real implementation of isdigit but it seems like it could: jbox.dk/sanos/source/lib/ctype.c.htmlKristopher
@Coodey: the real implementation of isdigit does not exist. There are many implementations, none of which is the "most real".Antons
G
0

Because there is no standard document to define how to represented bool by specified number, and for C language, non-zero is true and zero is false. so it depends on actual implementation .

Girondist answered 29/8, 2013 at 1:36 Comment(1)
Does that add anything that's not already in the other answer?Absonant

© 2022 - 2024 — McMap. All rights reserved.