Why are `true` and `false` both considered variables? - c++

I am new to C++ (and quite new to programming overall) and I was reading my C++ college book ("Starting out with C++ Early Objects" 9th edition by Gaddis, Walters and Muganda) when I came across a note on the bool data type.
"NOTE: Notice that true and false do not have quotation marks around them. This is because they are variables, not strings."
Now, from what I've learned, variables can be changed. I understand that a variable of the bool data type would be a variable, but how come true and false are considered variables?
From my understanding, false is stored as an integer value 0 and true as an integer value 1. I tried assigning values x where x is 0<x<0 to a bool and they all output 1 which made me come to the conclusion that true is also everything other than 0 (in other words, true is the same as !false?).
So if this is true, how come 'false' is considered a variable and not a constant?

You’re using a book that shows clear lack of understanding of the subject matter by the author. That book is lying to you. Throw it in the trash.
true and false are Boolean literals: they are a straightforward way of writing down a value of type bool. "true" and "false" are string literals – and, unfortunately, C++ can help you shoot yourself in the foot by converting them to their address, and then to a Boolean. So you get this wonderful nugget:
bool b1 = "false"; // string contents don’t matter
assert(b1 == true);
using book = bool;
book b2 = false;
assert(b2 == false);
The asserts are a way of writing true statements in the code: they mean that, at the point they appear, the condition in the parentheses must be true.
true and false are stored in whatever way the compiler desires – this is an implementation detail and the standard places no requirements here, other than true having to convert to 1 in numerical context, and false having to convert to 0 there. Usually they are not stored as integers, but bytes (char), i.e.
assert(sizeof(int) > sizeof(bool));

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.

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

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.

Does boolean true ever return 0? [duplicate]

This question already has answers here:
Can I assume (bool)true == (int)1 for any C++ compiler?
(5 answers)
Closed 7 years ago.
I was in a lecture and on the power point slides states that true would return 0 and false would return 1. I stated that in Visual Studio anything non zero is considered true, but is there a C++ standard that defines 0 as true?
Visual studio's results were disregarded as non standard but I doubt that it is.
bool tru = true; // returns 0
bool fal = false; // returns 1
Absolutely not. From the C++14 working draft (chosen here because I was able to find it easily, not because it's specific to C++14):
A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.
— http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf §4.5.6 (page 85)
Indeed, this behavior is common to most programming languages. Off the top of my head, for instance, Perl, Python, PHP, and Javascript all treat 0 as false and nonzero values as true. The only situation I can think of where 0 is "true" is in UNIX shell scripting, where an exit code of 0 is used for success and nonzero values are used for errors.
As mentioned in the accepted answer here, true is defined by the standard to compare equal to 1, and false to 0:
(§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."

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

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).