Reputation: 1574
In a piece of code I'm working on, I need to add 1 to an unsigned long
if some _Bool
is true.
I've been using
unsigned long l;
_Bool b;
... //stuff happens to both variables
if(b)
++l;
But I read in the C standard that the _Bool
type is classified as one of the "standard unsigned integer types" and it is guaranteed to express true as 1 and false as 0.
I replaced my code with this seemingly equivalent expression
unsigned long l;
_Bool b;
... //stuff happens to both variables
l+=b;
My compiler didn't complain and it seems to be working beautifully.
Is this guaranteed to work, or am I just exploiting the implementation of _Bool in my compiler?
Upvotes: 1
Views: 615
Reputation: 263357
It's almost guaranteed to work.
The standard doesn't quite say that a _Bool
object can only hold the values 0 and 1. And in fact sizeof(_Bool)
is at least 1, which means it has at least 8 bits, which means that it can in principle hold at least 256 distinct values.
If your code that assigned a value to b
is reasonably sane, you can safely assume its value is either 0 or 1. All conversions from other types to _Bool
are guaranteed to yield a value of 0 or 1.
But you can store a value other than 0 or 1 in a _Bool
object, though any method of doing so is likely to have undefined behavior.
An example:
#include <stdio.h>
#include <string.h>
int main(void) {
_Bool b;
char c = 42;
memcpy(&b, &c, 1);
long n = 0;
n += b;
printf("n = %ld\n", n);
}
The output on my system is
n = 42
But as long as you don't do silly things like this, and treat _Bool
with some minimal respect, you should be ok.
Upvotes: 3
Reputation:
Is this guaranteed to work
Yes, booleans in C are just integers, so adding a boolean to an integer is perfectly acceptable under any compiler I know of. C is weakly typed so there is no distinct difference between boolean and integer values. The only significance of a variable declared as _Bool
is that it automatically converts any value assigned to it to either 1 or 0.
_Bool x = 3; //x will be 1
int y = 7;
int z = y + x; //z will be 8
Upvotes: 1