Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the return type of isdigit() int instead of boolean?

Tags:

c++

I was reading the cplusplus reference for the isdigit() function, where I got this,

int isdigit ( int c );

Return Value: A value different from zero (i.e., true) if indeed c is a decimal digit. Zero (i.e., false) otherwise.

What does this term "different from zero" indicate, I mean why we can't just stick to 0 or 1. Also when I tested this function, it is always returning either 1 or 0, then why simply documentation can't say that isdigit function returns 1, instead of saying "different from zero".

like image 544
Mr. Twinkle Sharma Avatar asked Nov 14 '25 17:11

Mr. Twinkle Sharma


1 Answers

The reason is cross compatibility with C.

C itself didn't acquire a Boolean type until C99 and while that was over 20 years ago there's actually little justification for changing the definition of a widely used library function.

A explicit Boolean type has little practical advantage over the conventional use of 0 for false and non-zero for true other than readability.

By different from zero it means 'not zero'. It's near universal computing convention that when encoding Boolean values as numerical values 0 represents 'false' and all other values can be used to represent 'true'.

In general that's not something to worry about because constructs like if(isdigit(c)) will work because if() conforms to the same convention (in C and C++).

But if you're writing something like count+=isdigit(c) to perhaps count the number of digits in a string you may not get the answer you want.

As pointed out in the comments implementations may have reason for not returning 1 as true.

like image 113
Persixty Avatar answered Nov 17 '25 10:11

Persixty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!