Just read on an internal university thread:
#include <iostream>
using namespace std;
union zt
{
bool b;
int i;
};
int main()
{
zt w;
bool a,b;
a=1;
b=2;
cerr<<(bool)2<<static_cast<bool>(2)<<endl; //11
cerr<<a<<b<<(a==b)<<endl; //111
w.i=2;
int q=w.b;
cerr<<(bool)q<<q<<w.b<<((bool)((int)w.b))<<w.i<<(w.b==a)<<endl; //122220
cerr<<((w.b==a)?'T':'F')<<endl; //F
}
So a,b and w.b are all declared as bool. a is assigned 1, b is assigned 2, and the internal representation of w.b is changed to 2 (using a union).
This way all of a,b and w.b will be true, but a and w.b won't be equal, so this might mean that the universe is broken (true!=true)
I know this problem is more theoretical than practical (a sake programmer doesn't want to change the internal representation of a bool), but here are the questions:
Is this okay? (this was tested with g++ 4.3.3) I mean, should the compiler be aware that during boolean comparison any non-zero value might mean true?
Do you know any case where this corner case might become a real issue? (For example while loading binary data from a stream)
EDIT:
Three things:
bool and int have different sizes, that's okay. But what if I use char instead of int. Or when sizeof(bool)==sizeof(int)?
Please give answer to the two questions I asked if possible. I'm actually interested in answers to the second questions too, because in my honest opinion, in embedded systems (which might be 8bit systems) this might be a real problem (or not).
New question: Is this really undefined behavior? If yes, why? If not, why? Aren't there any assumptions on the boolean comparison operators in the specs?
If you read a member of a union that is a different member than the last member which was written then you get undefined behaviour. Writing an int member and then reading the union's bool member could cause anything to happen at any subsequent point in the program.
The only exception is where the unions is a union of structs and all the structs contain a common initial sequence, in which case the common sequence may be read.
Is this okay? (this was tested with g++ 4.3.3) I mean, should the compiler be aware that during boolean comparison any non-zero value might mean true?
Any integer value that is non zero (or pointer that is non NULL) represents true.
But when comparing integers and bool the bool is converted to int before comparison.
Do you know any case where this corner case might become a real issue? (For example while binary loading of data from a stream)
It is always a real issue.
Is this okay?
I don't know whether the specs specify anything about this. A compiler might always create a code like this: ((a!=0) && (b!=0)) || ((a==0) && (b==0)) when comparing two booleans, although this might decrease performance.
In my opinion this is not a bug, but an undefined behaviour. Although I think that every implementor should tell the users how boolean comparisons are made in their implementation.
If we go by your last code sample both a and b are bool and set to true by assigning 1 and 2 respectfully (Noe the 1 and 2 disappear they are now just true).
So breaking down your expression:
a!=0 // true (a converted to 1 because of auto-type conversion)
b!=0 // true (b converted to 1 because of auto-type conversion)
((a!=0) && (b!=0)) => (true && true) // true ( no conversion done)
a==0 // false (a converted to 1 because of auto-type conversion)
b==0 // false (b converted to 1 because of auto-type conversion)
((a==0) && (b==0)) => (false && false) // false ( no conversion done)
((a!=0) && (b!=0)) || ((a==0) && (b==0)) => (true || false) => true
So I would always expect the above expression to be well defined and always true.
But I am not sure how this applies to your original question. When assigning an integer to a bool the integer is converted to bool (as described several times). The actual representation of true is not defined by the standard and could be any bit pattern that fits in an bool (You may not assume any particular bit pattern).
When comparing the bool to int the bool is converted into an int first then compared.
Any real-world case
The only thing that pops in my mind, if someone reads binary data from a file into a struct, that have bool members. The problem might rise, if the file was made with an other program that has written 2 instead of 1 into the place of the bool (maybe because it was written in another programming language).
But this might mean bad programming practice.
Writing data in a binary format is non portable without knowledge.
There are problems with the size of each object.
There are problems with representation:
Integers (have endianess)
Float (Representation undefined ((usually depends on the underlying hardware))
Bool (Binary representation is undefined by the standard)
Struct (Padding between members may differ)
With all these you need to know the underlying hardware and the compiler. Different compilers or different versions of the compiler or even a compiler with different optimization flags may have different behaviors for all the above.
The problem with Union
struct X
{
int a;
bool b;
};
As people mention writing to 'a' and then reading from 'b' is undefined.
Why: because we do not know how 'a' or 'b' is represented on this hardware. Writing to 'a' will fill out the bits in 'a' but how does that reflect on the bits in 'b'. If your system used 1 byte bool and 4 byte int with lowest byte in low memory highest byte in the high memory then writing 1 to 'a' will put 1 in 'b'. But then how does your implementation represent a bool? Is true represented by 1 or 255? What happens if you put a 1 in 'b' and for all other uses of true it is using 255?
So unless you understand both your hardware and your compiler the behavior will be unexpected.
Thus these uses are undefined but not disallowed by the standard. The reason they are allowed is that you may have done the research and found that on your system with this particular compiler you can do some freeky optimization by making these assumptions. But be warned any changes in the assumptions will break your code.
Also when comparing two types the compiler will do some auto-conversions before comparison, remember the two types are converted into the same type before comparison. For comparison between integers and bool the bool is converted into an integer and then compared against the other integer (the conversion converts false to 0 and true to 1). If the objects being converted are both bool then no conversion is required and the comparison is done using boolean logic.
Normally, when assigning an arbitrary value to a bool the compiler will convert it for you:
int x = 5;
bool z = x; // automatic conversion here
The equivalent code generated by the compiler will look more like:
bool z = (x != 0) ? true : false;
However, the compiler will only do this conversion once. It would be unreasonable for it to assume that any nonzero bit pattern in a bool variable is equivalent to true, especially for doing logical operations like and. The resulting assembly code would be unwieldy.
Suffice to say that if you're using union data structures, you know what you're doing and you have the ability to confuse the compiler.
The boolean is one byte, and the integer is four bytes. When you assign 2 to the integer, the fourth byte has a value of 2, but the first byte has a value of 0. If you read the boolean out of the union, it's going to grab the first byte.
Edit: D'oh. As Oleg Zhylin points out, this only applies to a big-endian CPU. Thanks for the correction.
I believe what you're doing is called type punning:
http://en.wikipedia.org/wiki/Type_punning
Hmm strange, I am getting different output from codepad:
11
111
122222
T
The code also seems right to me, maybe it's a compiler bug?
See here
Just to write down my points of view:
Is this okay?
I don't know whether the specs specify anything about this. A compiler might always create a code like this: ((a!=0) && (b!=0)) || ((a==0) && (b==0)) when comparing two booleans, although this might decrease performance.
In my opinion this is not a bug, but an undefined behaviour. Although I think that every implementor should tell the users how boolean comparisons are made in their implementation.
Any real-world case
The only thing that pops in my mind, if someone reads binary data from a file into a struct, that have bool members. The problem might rise, if the file was made with an other program that has written 2 instead of 1 into the place of the bool (maybe because it was written in another programming language).
But this might mean bad programming practice.
One more: in embedded systems this bug might be a bigger problem, than on a "normal" system, because the programmers usually do more "bit-magic" to get the job done.
Addressing the questions posed, I think the behavior is ok and shouldn't be a problem in real world. As we don't have ^^ in C++ I would suggest !bool == !bool as a safe bool comparison technique.
This way every non-zero value in bool variable will be converted to zero and every zero is converted to some non-zero value, but most probably one and the same for any negation operation.
Related
I was messing around with some c++ code after learning that you cannot increment booleans in the standard. I thought incrementing booleans would be useful because I like compacting functions if I can and
unsigned char b = 0; //type doesn't really matter assuming no overflow
while (...) {
if (b++) //do something
...}
is sometimes useful to have, but it would be nice to not have to worry about integer overflow. Since booleans cannot take on any value besides 0 or 1, I thought that perhaps this would work. Of course, you could just have a boolean assigned to 1 after you do your operation but that takes an extra line of code.
Anyway, I thought about how I might achieve this a different way and I came up with this.
bool b = 0;
while (...)
if (b & (b=1)) ...
This turned out to always evaluate to true, even on the first pass through. I thought - sure, its just doing the bitwise operator from right to left, except that when I swapped the order, it did the same thing.
So my question is, how is this expression being evaluated so that it simplifies to always being true?
As an aside, the way to do what I wanted is like this I guess:
bool b = 0;
while (...) if (!b && !(b=1)) //code executes every time except the first iteration
There's a way to get it to only execute once, also.
Or just do the actually readable and obvious solution.
bool b = 0;
while (...) {
if (b) {} else {b=1;}
}
This is what std::exchange is for:
if (std::exchange(b, true)) {
// b was already true
}
As mentioned, sequencing rules mean that b & (b=1) is undefined behaviour in both C and C++. You can't modify a variable and read from it "without proper separation" (e.g., as separate statements).
There is no "strange behavior" here. The & operator, in your case is a bitwise arithmetic operator. These operator are commutative, so both operand must be evaluated before computing the resulting value.
As mentioned earlier, this is considered as undefined behavior, as the standard does not prevent computing + loading into a register the left operand, before doing the same to the second, or doing so in reverse order.
If you are using C++14 or above, you could use std::exchange do achieve this, or re-implement it quite easily using the following :
bool exchange_bool(bool &var, bool &&val) {
bool ret = var;
var = val;
return ret;
}
If you end up re-implementing it, consider using template instead of hard-coded types.
As a proper answer to your question :
So my question is, how is this expression being evaluated so that it simplifies to always being true?
It does not simplify, if we strictly follow the standard, but I'd guess you are always using the same compiler, which end up producing the same output.
Side point: You should not "compact" functions. Most of the time the price of this is less readability. This might be fine if you're the only dev working on a project, but on bigger project, or if you come back to your code later, that could be an issue. Last but not least, "compact" function are more error prone, because of their lack of readability.
If you really want shorter function, you should consider using sub-function that will handle part of the function computation. This would enable you to write short function, to quickly fix or update behavior, without impacting clarity.
I don't see what meaning you can assign to a "bitwise increment" operator. If I am right, what you achieve is just setting the low-order bit, which is done by b|= 1 (following the C conventions, this could have been defined as a unary b||, but the || was assigned another purpose). But I don't feel that this is a useful bitwise operation, and it can increment only once. IMO the standard increment operator is more bitwise.
If your goal was in fact to "increment" a boolean variable, i.e. set it to true (prefix or postfix), b= b || true is a way. (There is no "logical OR assignement" b||= true, and even less a "logical increment" b||||.)
I came up with a thought about the types of _Bool/ bool (stdbool.h) in C and bool in C++.
We use the boolean types to declare objects, that only shall hold the values of 0 or 1.
For example:
_Bool bin = 1;
or
bool bin = 1;
(Note: bool is a macro for _Bool inside the header file of stdbool.h.)
in C,
or
bool bin = 1;
in C++.
But are the boolean types of _Bool and bool really efficient?
I made a test to determine the size of each object in memory:
For C:
#include <stdio.h>
#include <stdbool.h> // for "bool" macro.
int main()
{
_Bool bin1 = 1;
bool bin2 = 1; // just for the sake of completeness; bool is a macro for _Bool.
printf("the size of bin1 in bytes is: %lu \n",(sizeof(bin1)));
printf("the size of bin2 in bytes is: %lu \n",(sizeof(bin2)));
return 0;
}
Output:
the size of bin1 in bytes is: 1
the size of bin2 in bytes is: 1
For C++:
#include <iostream>
int main()
{
bool bin = 1;
std::cout << "the size of bin in bytes is: " << sizeof(bin);
return 0;
}
Output:
the size of bin in bytes is: 1
So, objects of a boolean type do get stored inside 1 byte (8 bits) in memory, not just in one 1 bit, as it normally only shall require.
The reason why is discussed here: Why is a char and a bool the same size in c++?. This is not what my question is about.
My question are:
Why do we use the types of _Bool/ bool (stdbool.h) in C and bool in C++, if they do not provide a benefit in memory storage, as it is specificially pretended for use these types?
Why can´t I just use the types of int8_t or char (assuming char is contained of 8 bit (which is usually the case) in the specific implementation) instead?
Is it just to provide the obvious impression for a reader of the code, that the respective objects are used for 0 or 1/true or false purposes only?
Thank you very much to participate.
Why do we use the types of _Bool/ bool (stdbool.h) in C and bool in C++, if they do not provide a benefit in memory storage, as it is specificially pretended for use these types?
You already mentioned the reason in your question:
We use the boolean types to declare objects, that only shall hold the values of 0 or 1
The advantage of using boolean datatype specifically is because it can only represent true or false. The other integer types have more representable values which is undesirable when you want only two.
Why can´t I just use the types of int8_t or char (assuming char is contained of 8 bit (which is usually the case) in the specific implementation) instead?
You can. In fact, C didn't have a boolean data type until C99 standard. Note that downside of using int8_t is that it is not guaranteed to be provided by all systems. And porblem with char is that it may be either signed or unsigned.
But you don't need to, since you can use boolean data type instead.
This implies that there is difference when I use trueor false with boolean types in comparison to when I use these with char or int8_t. Could you state this difference?
Consider following trivial example:
int8_t i = some_value;
bool b = some_value;
if (i == true)
if (i)
if (b == true)
if (b)
For int8_t, those two conditionals have different behaviour, which creates opporunity for the behaviour to be wrong if the wrong form is chosen. For a boolean, they have identical behaviour and there is no wrong choice.
P.S. If you want to compactly store multiple boolean values (at the cost of multiple instructions per read and write), you can use std::bitset or std::vector<bool> for example. In C there are no analogous standard library utilities, but such functionality can be implemented with shifting and masking.
There's more than one sort of efficiency. Memory efficiency is one. Speed efficiency is another.
The original C language did not have a boolean type at all -- typically a programmer would use an int for boolean flags, 0 for false and 1 for true. If they were really concerned about memory efficiency, they might use a bitmap to store eight booleans in a byte, but this was generally only necessary in situations where memory was really scarce. But accessing an int is faster than accessing an int then unpacking its constituent bits.
_Bool/bool was introduced in C99. It reflects the common practice of storing booleans in an int.
However, it has the advantage that the compiler knows it's a boolean, so it's more difficult to accidentally assign it the value 3, add it to an integer, etc.
Most programming languages today store a boolean in a byte. Yes, it uses eight times more memory than necessary -- but it's fast, and it's rare to have so many booleans on the go at once that the waste becomes significant.
In many programming languages, the implementation is separate from the language spec -- Javascript's spec doesn't say how the Javascript runtime should store true or false. In C99 however you can rely on true being equivalent to integer 1.
If booleans are truly using too much of your system's memory, you can work with bitwise operations to store 8 booleans in an unsigned char or more in the larger types.
You can do that for runtime operations if necessary, or just when writing to an output format (if the problem is the size of records on filesystems, or network packets).
It's worth noting though, that in many, many modern applications, people are perfectly happy to represent false on the wire or on the filesystem as the 7 bytes [ '"', 'f', 'a', 'l', 's', 'e', '"' ]
One of the reasons for having bool as well as int is to increase the comprehensibility of the code to those who come after and try to maintain it.
Consider these
bool b;
int c;
if (b == c)
c = 2;
b = 2;
Now, I'd have said that comparing a boolean (true or false) with a number is very likely an error. So things like 'if (b == 1)' could indicate a coding error. I hope you'd agree that 'b = 2' is just wrong.
Benefits in memory storage (and I don't recall anything anywhere claiming that using boolean types reduced memory requirements) are not the only reason for language features.
This may sound as a really dumb question. But it has been bothering me for the past few days. And It's not only concerning the C++ Programming Language as I've added it's tag. My Question is that. In Computer Science Boolean (bool) datatype has only two possible values. 'true' or 'false'. And also, in Computer Science, 1 is true and 0 is false. So why does boolean exists at all? Why not we use an integer that can return only two possible values, Such as 1 or 0.
For example :
bool mindExplosion = true; // true!
int mindExplosion = 1; // true!!
// or we can '#define true 1' and it's the same right?
What am I missing?
Why does bool exist when we can use int?
Well, you don't need something as large as an int to represent two states so it makes sense to allow for a smaller type to save space
Why not we use an integer that can return only two possible values, Such as 1 or 0.
That is exactly what bool is. It is an unsigned integer type that represents true (1) or false (0).
Another nice thing about having a specific type for this is that it express intent without any need for documentation. If we had a function like (warning, very contrived example)
void output(T const & val, bool log)
It is easy to see that log is an option and if we pass false it wont log. If it were instead
void output(T const & val, int log)
Then we aren't sure what it does. Is it asking for a log level? A flag on whether to log or not? Something else?
What am I missing?
Expressiveness.
When a variable is declared int it might be used only for 0 and 1, or it might hold anything from INT_MIN..INT_MAX.
When a variable is declared bool, it is made explicit that it is to hold a true / false value.
Among other things, this allows the compiler to toss warnings when an int is used in places where you really want a bool, or attempt to store a 2 in a bool. The compiler is your friend; give it all the hints possible so it can tell you when your code starts looking funky.
I've got just a simple question about bitwise AND in C++.
I'm using it for single bits (a&8, a&4, a&2, a&1, etc.) and I want to get bool value as a return (if there's 1 on the position).
I may divide it by a number (like (a&8)/8), but it dosn't really look nice in my code (especially, that I'm using arrays and long names of variables).
Is there any other, better, way to code it?
Thanks in advance.
The best way is to convert the expression to a boolean value. This improves readability:
bool result;
result = 0 != (a & 8);
The comparison with 0 might be unnecessary since the compiled code will write true or false in the variable b. But this avoids a warning like:
warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)
The order or the comparison argument might be reversed if you don't like Yoda speech. It's a style that can help avoid accidental assignments in C programming language.
If you want to be explicit, compare with 0:
const bool maskSet = (a & 8) != 0;
That's the cleanest way I know of. Dividing is much stranger, since that still leaves the conversion from an integer to a boolean implicit. The comparison operator makes it explicit.
I have this class which has a private bool member variable call positive. I want to check to see if both my class and the number I am adding to it are both positive so I wrote the expression
positive == (n > 0) //n is of type int
But for some reason when both are positive this evaluates to false. I then did a cout on positive and it has a value of 204! I though a boolean only holds 1 or 0. That would be why this is evaluating to false but why is that and how do I fix it? I am using Visual Studio 2013.
Just to clarify it should be == because I want to know if the sign is the same. So I want it to be true if both are negative or both are positive. I think I solved the problem which was that positive in one particular test case wasn't being initialized. But still why would a bool variable even if uninitialized contain a value larger and 1?
As per the standard, getting the value of an uninitialized variable is undefined behavior.
Since the actual size of a bool can be more than one bit, a bool variable containing rubbish can even hold bad values like 254. Welcome in the C++ hell!
And since (n > 0) evaluates to 1, 254 == 1 is false.
The bug is most likely due to the fact that positive never got a meaningful value since the object that contains it come into existence.
Search for a positive = something into your code and see if it is executed at least once before you use it.
Edited after Konrad comment:
The problem is most likely due to the fact that == is implemented between int-s and not bool-s relying on a bool-to-int promotion assuming the implementation of bool use 0 for false and 1 for true (and since && and || between int-s assume 0 for false and non-zero for true, bool-to-int promotion can be an identity).
This can be seen as a "compiler unfairness", but -since in the space of integer there is one false and bilions of trues- if operator==(bool,bool) was applied, there where more chance the uninitialized bug wold have been not discovered.
Treating bool as int in the arithmetic operations (not logic ones) makes bad-bool values to come out, thus revealing the bug.
Of course, since behind it there is an UB, it's all in an implementation choice. And it is int the freedom of each reading this to think I'm try to sell a bug as a feature.
Oh, you have a == where you should have an =.
The == doesn't assign, it checks for equality
Should be
bool positive = (n > 0) //n is of type int
bool generally holds only 1 or 0 after assignment. The only reason I can imagine you would see 204 in a bool is if the variable was uninitialized (so it had a junk value).