Why is the return type of isdigit() int instead of boolean? - 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".

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.

Related

no comparison in if() judgement but seems give a boolean value

if(!word.size()){
return true;
}
whole code screenshot
how here use string.size() lonely to return a boolean value?
I googled the string.size() method although i already know it returns a int value,but here it works like a true/false method;
Lots of things in C++ can be coerced to Booleans. Off the top of my head.
Booleans are trivially convertible to Booleans
Numbers (int or double) can be converted to Boolean; zero is false and anything else is true
Streams (like fstream instances or cout, for instance) can be converted to Boolean and are true if the stream is in "good" condition or false if there's a problem
As indicated in the comments, you shouldn't use this in real code. if (!word.size()) is silly and confusing an should only be seen in code golf challenges. Coding isn't just about making the computer understand what you mean; it's about making sure future readers (including yourself six months down the line) understand as well. And if (word.empty()) conveys the exact same intent to the computer but is much more understandable to the human reader at a glance.
So why does C++ allow this if it's discouraged? Historical reasons, mostly. In the days of C, there was no dedicated bool type. Comparisons returned an integer, and the convention was that 0 meant "false" and anything else (usually 1) meant true. It was the programmer's job to remember which things were Booleans and which were actual integers. C++ came along and (rightly) separated the two, making a special type called bool. But for compatibility with C, they left in the old trick of using integers as Booleans. Successor languages like Java would go on to remove that capability. if (myInteger) is illegal in Java and will give a compiler error.
The language checks if the condition inside the conditional is true or false. In this case, the int value gets converted into a boolean. If the size returns 0 this will get converted to false, any other value will be converted to true.

Strange definition of FALSE and TRUE, why? [duplicate]

This question already has answers here:
Why #define TRUE (1==1) in a C boolean macro instead of simply as 1?
(8 answers)
Closed 9 years ago.
In some code I am working on I have come across strange re-definitions of truth and falsehood. I have seen such things before to make checks more strict/certain, but this one is a little bizarre in my mind and I wonder if anyone can tell me what could be a good reason for such definitions, see below with my comments next to them:
#define FALSE (1 != 1) // why not just define it as "false" or "0"?
#define TRUE (!FALSE) // why not just define it as "true" or "1"?
There are many other strange oddities in this code base. Like there are re-definitions for all the standard types like:
#define myUInt32 unsigned integer // why not just use uint32_t from stdint?
All these little "quirks" make me feel like I am missing something obvious, but I really can't see the point :(
Note: Strictly this is c++ code, but it could have been ported from a 'c' project.
The intent appears to be portability.
#define FALSE (1 != 1) // why not just define it as "false" or "0"?
#define TRUE (!FALSE) // why not just define it as "true" or "1"?
These have boolean type in languages that support it (C++), while providing still-useful numeric values for those that don't (C — even C99 and C11, apparently, despite their acquisition of explicit boolean datatypes).
Having booleans where possible is good for function overloading.
#define myUInt32 unsigned integer // why not just use uint32_t from stdint?
That's fine if stdint is available. You may take such things for granted, but it's a big wide world out there! This code recognises that.
Disclaimer: Personally, I would stick to the standards and simply state that compilers released later than 1990 are a pre-requisite. But we don't know what the underlying requirements are for the project in question.
TRWTF is that the author of the code in question did not explain this in comments alongside.
#define FALSE (1 != 1) // why not just define it as "false" or "0"?
I think it is because the type of the expression (1!=1) depends on the language's support for boolean value — if it is C++, the type is bool, else it is int.
On the other hand 0 is always int, in both languages, and false is not recognized in C.
Strictly this is c++ code, but it could have been ported from a 'c' project.
This is about portability as mentioned previously, but it actually goes far beyond. It's a clever exploit of the language definitions in order to comply with the languages.
These absurd looking macros are not as absurd as they appear at first glance, but they are in fact ingenious, as they guarantee for both C and C++ that TRUE and FALSE have the correct values (and type) of true and false (even if the compiler is a C compiler which doesn't have those keywords, so you can't trivially write something like #define TRUE true).
In C++ code, such a construct would be useless, since the language defines true and false as keywords.
However, in order to have C and C++ seamlessly interoperate in the same code base, you need "something" that works for both (unless you want to use a different code style).
The way these macros are defined is a testimony of the C++ standard on being explicitly vague about what values true and false actually have. The C++ standard states:
Values of type bool are either true or false.
[...]
A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.
[...]
A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.
Note how it says that two particular values exist and what their names are, and what corresponding integer values they convert to and from, but it does not say what these values are. You might be inclined to think that the values are obviously 0 and 1 (and incidentially you might have guessed right), but that's not the case. The actual values are deliberately not defined.
This is analogous to how pointers (and in particular the nullpointer) are defined. Remember that an integer literal of zero converts to the null pointer and that a nullpointer converts to false, compares equal... blah blah... etc etc.
A lot is being said about which converts to what and whatnot, but it doesn't say anywhere that a null pointer has to have a binary representation of zero (and in fact, there exist some exotic architectures where this isn't the case!).
Many of them have historical reasons such as old codes migrated from C, codes from non-standard C++ compilers, cross compiler codes (portability), to support backward compatibility, following code styles, bad habits.
There were some compilers which had not <cstdint> for integer types like uint32_t, or they had not <cstdbool>. A good programmer had to define everything and use pre-processors heavily to make his program well defined over different compilers.
Today, we can use <cstdint>, true/false, <cstdbool>, ... and everyone is happy!
The nice thing about this defintion is to avoid an implicit conversion from TRUE or FALSE to an integer. This is useful to make sure the compiler can't choose the wrong function overload.
C didn't have a native boolean type, so you couldn't strictly use "false" or "true" without defining them elsewhere - and how would you then define that?
The same argument applies to myUInt32 - C originally didnt have uint32_t and the other types in stdint, so this provides a means of ensuring you are getting the correct size integer. If you ported to a different architecture, you just need to change the definition of myUInt32 to be whatever equates to an unsigned integer 32 bits wide - be that a long, or a short.
There is a nice explanation which states the difference between false and FALSE. I think it might help in understanding bit further though most of the answers have explained it.
here

Is it always safe to assume that values of ..stream::int_type are >= 0 except for eof

I want to parse a file and use an std::stringstream to parse its contents. I use get() to read it character by character, which yields an std::stringstream::int_type. Now in certain cases I want to use a lookup table to convert ascii characters into other values (for example, to deterime whether a certain character is allowed in an identifier or not).
Now can I assume that the values I get from get() are non-negative, unless it is std::stringstream::traits_type::eof()? (And hence use them as indices for the lookup tables).
I couldn't find anything in the standard regarding that, which might be due to a lack of understanding on my part how this whole bytes to characters thing works in C++.
First let look at the more general case of basic_stringstream.
You can't assume that eof() is negative (I see the constraint nowhere and the C standard states The value of the macro WEOF may differ from that of EOF and need not be negative.)
In general, int_type comes from the trait parameter and the description of int_type for character traits doesn't mandate that to_int_type returns something positive.
Now, stringsteam is basic_stringstream<char> and thus use char_traits<char>; eof is negative but I haven't found a mandate that to_int_type has to non-negative values (it isn't in 21.2.3.1 and I see no way to deduce it from other constraints), but I wonder if I miss something as my expectation was that to_int_type(c) had to be equivalent to (int)(unsigned char)c -- it is the case for the GNU standard C++ library and I somewhat expect to get the same behavior as in C where functions taking or returning characters in int return non-negative values for characters.)
For information, the other standard specialization of char_traits:
char_traits<char16_t> and char_traits<char32_t> have an unsigned int_type, so even eof() is positive;
char_traits<wchar_t>::to_int_type isn't mandated to return a positive value for non eof() input either (but in contrast with char_traits<char> I didn't expect such mandate to be there).

VB6 and C++ boolean literals

I am learning C++. I come from a background of: .NET and VB6.
I am intrigued about what the following webpage says about booleans: http://msdn.microsoft.com/en-us/library/ff381404(v=vs.85).aspx i.e.
"Despite this definition of TRUE, however, most functions that return a BOOL type can return any non-zero value to indicate Boolean truth. Therefore, you should always write this:
// Right way.
BOOL result = SomeFunctionThatReturnsBoolean();
if (result)
{
...
}
"
Does this apply to VB6 as well i.e. is there a problem saying: If BooleanValue = True Then?
The Windows API was designed to be used from C programs. Which until C99 didn't have a bool type. And still doesn't completely, C99 was never implemented by the Microsoft compiler for example. So they had to come up with a workaround, one that's highly compatible with the way C compilers deal with logical values. An int where 0 is false and anything else is true. Thus the advice.
VB6 has a dedicated Boolean type and keywords for the literal values True and False so doesn't quite have the same problem. You can however still get into trouble with poorly written COM servers. The underlying integral value for True is -1, highly incompatible with many other languages' implementation of a logical boolean type. Including C. There's a good reason for VB6 being the oddball, its And and Or operators don't distinguish between a logical and a arithmetic and/or. By making True equal to -1 and False equal to 0 there is no difference. Trouble can arise when a COM server returns a 1 to indicate true instead of VARIANT_TRUE.
But most of all, writing If booleanVariable = True Then is just ugly and nails on the blackboard for many programmers. Just write If booleanVariable Then and be done with it.
Not in VB, no, as True/False are real boolean values. In C/C++ however, BOOL is just a #define of int, thus you can assign a BOOL variable any integer value (TRUE in C is a #define of 1 (usually) and FALSE a #define of 0).
If you want better overlap with your VB experience, use the bool datatype in C++ which uses actual true/false values.
EDIT: Of course, in VB you say If BooleanValue = TRUE. In C++, the equivalent is if (BooleanValue == true) (note the ==, which is a comparison operator, as opposed to = which is an assignment operator), but in C++ you can skip the == true comparison and just use if (BooleanValue).

What does double not (!!) used on a non-boolean variable do? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Double Negation in C++ code.
I am working with production code where I have run across statements like this a few times:
Class.func(!!notABool);
The first couple of times I dismissed it as a programmer quirk (maybe to emphasize that it is a conditional statement rather than a number being passed into func?) but I have run across several statements that use the above and now I am wondering whether it actually makes a difference or not. In most cases notABool is a number(int, float, double... I have seen all 3) My initial guess was that it is akin to typing:
Class.func((bool)notABool);
but I am not entirely sure?
Yes, functionally it is exactly the same as doing (bool) notABool.
By definition, in C++ language the operand of ! is implicitly converted to bool type, so !!notABool is really the same as !! (bool) notABool, i.e. the same as just (bool) notABool.
In C language the !! was a popular trick to "normalize" a non-1/0 value to 1/0 form. In C++ you can just do (bool) notABool. Or you can still use !!notABool if you so desire.
For primitive types, yes, it's essentially equivalent to:
!(notABool != 0)
which in turn is equivalent to:
(bool)notABool
For non-primitive types, it will be a compiler error, unless you've overloaded operator!, in which case, it might do anything.
It's a legacy idiom from C, where it meant "normalize to 0 or 1". I don't think there's a reason to use it in C++ other than habit.
It's converting BOOL (define for int) to c++ bool. BOOL is a define that in some cases for true can contain different integer values. So for example BOOL a = (BOOL)1; and BOOL b =(BOOL)2; both pass check for true. But if you'll try to compare you'll find that a not equals b. But after conversion !!a equals !!b.
(bool)notABoo - is not akin, because you'll convert type of variable byte still'll have different values. !! converts not only type but in some cases values too.