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