Martin Wells wrote:
I come from C++, and there's a type called "bool" in C++. It works
exactly like any other integer type except that when promoted, it
either becomes a one or a zero, so you can you bitwise operators as if
they were logical operators:
bool a = 5, b = 6;
if (a == b) DoSomething; /* This will execute */
What type is commonly used in C for playing around with boolean
values?
It used to be that C programmers did not rely on the boolean crutch,
since various kinds of integers serve quite well without losing
information. However, for some reason this expensive way to store
single bits has enough appeal that we now have:
#include <stdbool.h>
#include <stdio.h>
int main(void)
{
bool a_bool = 5, b_bool = 6; /* <stdbool.hcauses 'bool' to
expand to '_Bool' */
_Bool a_Bool = 5, b_Bool = 6;
unsigned int a_int = 5, b_int = 6;
printf("using 'bool' versions of a and b\n"
"a_bool = %u, compares %sequal to 'true'\n"
"b_bool = %u, compares %sequal to 'true'\n"
"the value of a_bool == b_bool is %u\n"
"the value of (a_bool == b_bool) == true is %u\n\n",
a_bool, (a_bool == true) ? "" : "not ",
b_bool, (b_bool == true) ? "" : "not ",
a_bool == b_bool, (a_bool == b_bool) == true);
printf("using '_Bool' versions of a and b\n"
"a_Bool = %u, compares %sequal to 'true'\n"
"b_Bool = %u, compares %sequal to 'true'\n"
"the value of a_Bool == b_Bool is %u\n"
"the value of (a_Bool == b_Bool) == true is %u\n\n",
a_Bool, (a_Bool == true) ? "" : "not ",
b_Bool, (b_Bool == true) ? "" : "not ",
a_Bool == b_Bool, (a_Bool == b_Bool) == true);
printf("using 'unsigned int' versions of a and b\n"
"a_bool = %u, compares %sequal to 'true'\n"
"b_bool = %u, compares %sequal to 'true'\n"
"the value of a_int == b_int is %u\n"
"the value of (a_int == b_int) == true is %u\n\n",
a_int, (a_int == true) ? "" : "not ",
b_int, (b_int == true) ? "" : "not ",
a_int == b_int, (a_int == b_int) == true);
return 0;
}
[output]
using 'bool' versions of a and b
a_bool = 1, compares equal to 'true'
b_bool = 1, compares equal to 'true'
the value of a_bool == b_bool is 1
the value of (a_bool == b_bool) == true is 1
using '_Bool' versions of a and b
a_Bool = 1, compares equal to 'true'
b_Bool = 1, compares equal to 'true'
the value of a_Bool == b_Bool is 1
the value of (a_Bool == b_Bool) == true is 1
using 'unsigned int' versions of a and b
a_bool = 5, compares not equal to 'true'
b_bool = 6, compares not equal to 'true'
the value of a_int == b_int is 0
the value of (a_int == b_int) == true is 0