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;
}
The isdigit(c) is a function in C which can be used to check if the passed character is a digit or not. It returns a non-zero value if it's a digit else it returns 0. For example, it returns a non-zero value for '0' to '9' and zero for others.
The isdigit() function is a predefined function of the C library, which is used to check whether the character is a numeric character from 0 to 9 or not. And if the given character is a numeric number or digit, it returns a true Boolean value or non-zero; else, it returns zero or false value.
The function isdigit() is used to check that character is a numeric character or not. This function is declared in “ctype. h” header file. It returns an integer value, if the argument is a digit otherwise, it returns zero.
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
cconforms 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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With