Home > Back-end >  Why do functions like isdigit() return a random non-zero value?
Why do functions like isdigit() return a random non-zero value?

Time:07-01

In the second edition of The C Programming Language book, it is said that functions like isdigit may return any non-zero value for true. Why do functions like isdigit return a random non-zero value for true instead of something standardized like 1 (just like logical expressions do)? Also, in my tests, the result of the isdigit function was always 2048 for true. Is this fully random or tied to something, or is this 2048 value the same for everyone?

Compiler that I use: GCC 12.1.0

CodePudding user response:

A common implementation of isdigit and the related routines such as isalpha is to use an array indexed by character value in which each element of the table is a set of bit flags for the properties. There is one bit that is set if the character is a digit, one that is set if the character is a letter, one that is set if it is a white-space character, and so on.

Then the <ctype.h> functions can be implemented largely as table[x] & mask, where the mask selects the desired bit(s) for the test.

This results in a result that is zero if the character not in the tested set and non-zero if it is. Because the non-zero value is the tested flag(s), it is not one unless the applicable flag happened to use bit zero, with value one. For example, if the bit used to indicate a digit is bit ten, with value 1024, then isdigit will always return zero or 1024.

This suffices to serve the purposes of the character classification functions. Adding a requirement they return only one or zero would require an extra step, so it would be wasteful, and therefore this requirement was not added to the specification.

  •  Tags:  
  • c gcc
  • Related