I want to know if bool variable can be null, or it must have to be true or false:
Base on Arduino description: A bool holds one of two values, true or false. (Each bool variable occupies one byte of memory.)
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It only takes a minute to sign up.
Sign up to join this communityA bool
value must be either 0
or 1
, or false
and true
respectively. It is undefined behavior for it to be any other value. When assigning a value to a bool
, the compiler will automatically force it to be 0 if it is already 0, or 1 if it is not.
However, as it is a full byte, it is possible to store another value. As mentioned before, however, this is undefined behavior. This means that if it ever happens, or will absolutely happen, the program can do anything: for example, crash the program, output random data, or act like it's truthy, falsy, or both! In fact, that can (again, no guarantees) happen if you store the value 2:
#include <cstdio>
int main() {
union b_c {
unsigned char c;
bool b;
};
b_c c;
c.c = 2;
if(c.b) puts("true!");
if(!c.b) puts("false!");
}
(this is designed to run on a computer, but the same thing could happen on an Arduino). Check out what happens when you run it: it outputs both true!
and false!
! This obviously doesn't make sense, but because we violate the rules by making a bool
2
, we loose all guarantees.
So, how is this relevant to your question? There's no valid value a bool
can store other than true
and false
. In C++, null
is defined as "an integer literal with value zero". So, if you were to assign null
to a bool
, it would be stored as false. If you want a separate null value, you're better off using another type that takes up a single byte (e.g. unsigned char
or uint8_t
, same thing) and storing e.g. 0
for false
, 1
for true
, and 2
for null.
0
or 1
in a bool
, i.e. a single bit. However, because you can't address single bits, each bool
takes up a full byte, even though you can't use the other 7 buts.
Jul 20, 2021 at 21:58
int
. There is no guarantee that it takes just 8 bits (chapter 8.3.3 in the C++17 standard). However, some systems support bit accesses (8051 microcontroller, for example), and some compilers for these support 1-bit bool
s.
Jul 21, 2021 at 6:48
A bool is literally that - a boolean value. So either 1 or 0 - true or false.
In C only pointers can be NULL. Every other primitive type is a value, and NULL is not a value.