C++ Boolean Algebra - c++

I have declared some variable as Boolean and I was hoping that C++ would know what to do when I did some boolean addition but it's not happening the way I would like it to. How do I get it to work.
#include<iostream>
using namespace std;
int main()
{
bool x,j;
x=0;
j=1;
for(int i=0;i<10;i++)
{
cout << x;
x=x+j;
}
return 0;
}
I am getting the output as
011111111
whereas I was hoping to get
0101010101
I was hoping that Boolean variables would mod out by 2. So if
x=1 then
x+1 = 0
x+1+1=1
x+1+1+1=0
and so on.
Am I confusing boolean algebra with base-2 algebra?
Thanks

bool x,j;
x=x+j;
This statement automatically promotes x and j to type int before adding them. Then the assignment converts back to bool in the usual way: 0 becomes false, but any other number , including 2, becomes true.
You can get Z_2 addition by using the ^ (xor) operator instead:
x = x^j;

C/C++ provide a range of bitwise operators: &, |, ^, ~, which generally work on booleans because true is converted to the integer 1 and false to 0.
But you can also use real boolean operators:
&& conjunction
|| disjunction
!= exclusive or (what you regard as addition)
! not

Related

AND Operation for -1

While implementing logical operations in the code, I discovered a phenomenon where it should not be entered in the if statement.
It turns out that this is the AND (&&) operation of -1 and natural numbers.
I don't know why the value 1 is printed in the same code below.
I ran direct calculations such as 1's complement and 2's complement, but no 1 came out.
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = -1;
int c = a && b;
printf("test = %d",c);
return 0;
}
The expression a && b is a bool type and is either true or false: it is true if and only if both a and b are non-zero, and false otherwise. As your question mentions complementing schemes (note that from C++20, an int is always 2's complement), -0 and +0 are both zero for the purpose of &&.
When assigned to the int type c, that bool type is converted implicitly to either 0 (if false) or 1 (if true).
(In C the analysis is similar except that a && b is an int type, and the implicit conversion therefore does not take place.)

How to convert int to short int using bitwise operators?

For example:
short a = 10;
int b = a & 0xffff;
Similarly if I want to convert from int to short, how do I do using bitwise operators? I don't want to use the usual casting using (short).
If you want sign extension:
int b = a;
If you don't (i.e. negative values of a will yield (weird) positive values of b)
// note that Standard Conversion of shorts to int happens before &
int b = a & std::numeric_limits<unsigned short>::max();
Doing bit-operations on signed types may not be a good idea and lead to surprising results: Are the results of bitwise operations on signed integers defined?. Why do you need bit-operations?
short int2short(int x) {
if (x > std::numeric_limits<short>::max()) {
// what to do now? Throw exception, return default value ...
}
else if (x < std::numeric_limits<short>::min()) {
// what to do now? Throw exception, return default value ...
} else
{
return static_cast<short>(x);
}
}
This could generalized into a template method and also have policies for the error cases.
Why not using (short)? That's the easiest way and gets what you want.
Unless it's an interview problem, then you need to assume how many bits a short and a int contains. If the number is positive, just using bitwise AND. If the number is negative, flip it to positive number, and do bitwise AND. After AND, you need to change the highest bit to 1.

Can I use the not operator in C++ on int values?

Strange question, but someone showed me this,
I was wondering can you use the not ! operator for int in C++? (its strange to me).
#include <iostream>
using namespace std;
int main()
{
int a=5, b=4, c=4, d;
d = !( a > b && b <= c) || a > c && !b;
cout << d;
system ("pause");
return 0;
}
Yes. For integral types, ! returns true if the operand is zero, and false otherwise.
So !b here just means b == 0.
This is a particular case where a value is converted to a bool. The !b can be viewed as !((bool)b) so the question is what is the "truthness" of b. In C++, arithmetic types, pointer types and enum can be converted to bool. When the value is 0 or null, the result is false, otherwise it is true (C++ §4.1.2).
Of course custom classes can even overload the operator! or operator<types can be convert to bool> to allow the !b for their classes. For instance, std::stream has overloaded the operator! and operator void* for checking the failbit, so that idioms like
while (std::cin >> x) { // <-- conversion to bool needed here
...
can be used.
(But your code !( a > b && b <= c) || a > c && !b is just cryptic.)
Originally, in C (on which C++ is based) there was no Boolean type. Instead, the value "true" was assigned to any non-zero value and the value "false" was assigned to anything which evaluates to zero. This behavior still exists in C++. So for an int x, the expressions !x means "x not true", which is "x not non-zero", i.e. it's true if x is zero.
You can, !b is equivalent to (b == 0).
The test for int is true for non-zero values and false for zero values, so not is just true for zero values and false for non-zero values.
The build-in ! operator converts its argument to bool. The standard specifies that there exists a conversion from any arithmetic type(int, char,.... float, double...) to bool. If the source value is 0 the result is true, otherwise it is false

Is there an Non-Short circuited logical "and" in C++?

tl;dr: Is there a non-short circuit logical AND in C++ (similar to &&)?
I've got 2 functions that I want to call, and use the return values to figure out the return value of a 3rd composite function. The issue is that I always want both functions to evaluate (as they output log information about the state of the system)
IE:
bool Func1(int x, int y){
if( x > y){
cout << "ERROR- X > Y" << endl;
}
}
bool Func2(int z, int q){
if( q * 3 < z){
cout << "ERROR- Q < Z/3" << endl;
}
}
bool Func3(int x, int y, int z, int q){
return ( Func1(x, y) && Func2(z, q) );
}
Of course, the conditionals aren't quite that simple in the functions, and yes, I realize that I could use temporary variables to store the returns of the two functions and then do the "short-circuit" logic on the temporary variables, but I was wondering if there was an "elegant" language solution to keep the one-line return in Func3 while still getting the logging messages from both functions.
Summary of responses:
The "bitwise" operators | and & can be used to get the effect, but only if the return type is bool. I found no mention of this in the ANSI C++ spec. From what I can tell, this works because the "bool" is converted to an int (true = 1, false = 0), and then the bitwise operator is used, then it is converted back to a bool.
The Operators "+" and "*" can also be used. This is not mentioned in the ANSI C++ Spec, but probably works because of the same reason as above. "+" give "or" because true is converted to 1, and then anything other than 0 is converted back to true. "*" works for "and" because 1 (true) * 0 (false) == 0(false) and 1(true) * 1(true) == 1(true)
Both of these seem to rely on implicit type conversion to integer and then back to bool. Both of these will likely mess up whomever tries to maintain the code.
Other responses boil down to "Just use temporaries" or "Implement your own" which was not the question. The goal was to see if there was already an operator implemented in the C++ standard to do it.
The & operator performs logical "and" operation for bool operands and is not short circuited.
It's not a sequence point. You cannot rely on the order of evaluation of the operands. However, it's guaranteed that both operands are evaluated.
I do not recommend doing this. Using temporary variables is a better solution. Don't sacrifice readability for "clever code".
and yes, I realize that I could use temporary variables to store the returns of the two functions and then do the "short-circuit" logic on the temporary variables, but I was wondering if there was an "elegant" language solution to keep the one-line return in Func3 while still getting the logging messages from both functions.
That would be the "elegant" solution :). Relying on the side effects of the evaluation order would be far from elegant, error prone, and hard to understand for the next developer who wanders into your project. Relying on the side effects of course contrasts with something like the following snippet, which is a completely logical and valid use case for relying on evaluation order alone:
if ( obj != NULL && obj->foo == blah ) { /* do stuff */ }
Yes there are built in operators for doing this.
+ does a non short circuiting OR and * does an AND. ☺
#include <iostream>
using namespace std;
void print(bool b)
{
cout << boolalpha << b << endl;
}
int main()
{
print(true + false);
print(true * false);
}
Output:
true
false
You can trivially write your own.
bool LongCircuitAnd( bool term1, bool term2 ) { return term1 && term2; }
bool Func3(int x, int y, int z, int q){
return LongCircuitAnd( Func1(x,y), Func2(z,q) );
And if you want to be very fancy, you could even inline it!!!
Okay, Okay, if you really really don't want the terrible overhead of calling a function.
bool Func3(int x, int y, int z, int q){
return ((int)Func1(x,y)) * ((int)Func2(z,q));
But I don't consider that elegant. It its conceivable that an overly smart compiler could short circuit this...
If you want to use the temporary variables, but keep the return to a single statement, you could use the comma operator:
return (b1=Func1()), (b2=Func2()), (b1&&b2);
The comma operator forces a sequence point, so each one evaluates its left operand, discards the result, then evaluates its right operand.
Another possibility, but one I'd tend to recommend against, would be for the two functions to return a type that overloads the '&&' operator. Since an overloaded operator invokes a function, it always evaluates both operands, even in cases (like &&) where the built-in operator does not -- usually that's something of a problem, but in this case it's exactly what you want:
class mybool {
bool value;
public:
bool operator&&(mybool const &other) const {
return value && other.value;
}
};
mybool Func1(int, int);
mybool Func2(int, int);
bool Func3(int x, int y, int z, int q) {
return Func1(x, y) && Func2(z,q);
}
While this works, it seems to me like it's just a bit too "clever" -- something that wouldn't be at all obvious to most readers. A different name for mybool might help, but offhand I can't think of one that reflects the intent very well without becoming so verbose it would be a net loss.
Yes. The overloaded versions of operator&& and operator|| do not short-circuit — they evaluate both operands even if the left-hand operand "determines" the outcome... (Source)
That being said, don't overload operator&& or operator||. Be nice to your maintenance programmers who will look at && or || and assume that they do short circuit.
A near-universal but often undocumented non-Standard operator was introduced for exactly this purpose, pioneered by GCC alongside x ?: y (x if non-zero else y), and the now sadly removed >? and <? min/max operators and their compound assignment forms (see http://gcc.gnu.org/onlinedocs/gcc/Deprecated-Features.html). Sadly, with & and && already in use, they seem to have been scraping the bottom of the barrel to find an appropriate character sequence, but that's just my opinion - would welcome any historical explanations for why this might have been chosen.
So, while it's not currently as well known as many other operators, the >! operator (properly but boringly called "long-circuit and", but colloquially "bigger knot" by those in the know) was added by most C and C++ compilers (include GCC and even MSVC++) to satisfy this requirement:
bool f1() { ... }
bool f2() { ... }
...
bool f3() { return f1() >! f2(); }
Do take it for a spin ;-).

Using bitwise operators for Booleans in C++

Is there any reason not to use the bitwise operators &, |, and ^ for "bool" values in C++?
I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression. I also sometimes want all parts of a condition to be evaluated whether the result is true or not (rather than short-circuiting), so I use & and |. I also need to accumulate Boolean values sometimes, and &= and |= can be quite useful.
I've gotten a few raised eyebrows when doing this, but the code is still meaningful and cleaner than it would be otherwise. Is there any reason NOT to use these for bools? Are there any modern compilers that give bad results for this?
|| and && are boolean operators and the built-in ones are guaranteed to return either true or false. Nothing else.
|, & and ^ are bitwise operators. When the domain of numbers you operate on is just 1 and 0, then they are exactly the same, but in cases where your booleans are not strictly 1 and 0 – as is the case with the C language – you may end up with some behavior you didn't want. For instance:
BOOL two = 2;
BOOL one = 1;
BOOL and = two & one; //and = 0
BOOL cand = two && one; //cand = 1
In C++, however, the bool type is guaranteed to be only either a true or a false (which convert implicitly to respectively 1 and 0), so it's less of a worry from this stance, but the fact that people aren't used to seeing such things in code makes a good argument for not doing it. Just say b = b && x and be done with it.
Two main reasons. In short, consider carefully; there could be a good reason for it, but if there is be VERY explicit in your comments because it can be brittle and, as you say yourself, people aren't generally used to seeing code like this.
Bitwise xor != Logical xor (except for 0 and 1)
Firstly, if you are operating on values other than false and true (or 0 and 1, as integers), the ^ operator can introduce behavior not equivalent to a logical xor. For example:
int one = 1;
int two = 2;
// bitwise xor
if (one ^ two)
{
// executes because expression = 3 and any non-zero integer evaluates to true
}
// logical xor; more correctly would be coded as
// if (bool(one) != bool(two))
// but spelled out to be explicit in the context of the problem
if ((one && !two) || (!one && two))
{
// does not execute b/c expression = ((true && false) || (false && true))
// which evaluates to false
}
Credit to user #Patrick for expressing this first.
Order of operations
Second, |, &, and ^, as bitwise operators, do not short-circuit. In addition, multiple bitwise operators chained together in a single statement -- even with explicit parentheses -- can be reordered by optimizing compilers, because all 3 operations are normally commutative. This is important if the order of the operations matters.
In other words
bool result = true;
result = result && a() && b();
// will not call a() if result false, will not call b() if result or a() false
will not always give the same result (or end state) as
bool result = true;
result &= (a() & b());
// a() and b() both will be called, but not necessarily in that order in an
// optimizing compiler
This is especially important because you may not control methods a() and b(), or somebody else may come along and change them later not understanding the dependency, and cause a nasty (and often release-build only) bug.
The raised eyebrows should tell you enough to stop doing it. You don't write the code for the compiler, you write it for your fellow programmers first and then for the compiler. Even if the compilers work, surprising other people is not what you want - bitwise operators are for bit operations not for bools.
I suppose you also eat apples with a fork? It works but it surprises people so it's better not to do it.
I think
a != b
is what you want
Disadvantages of the bitlevel operators.
You ask:
“Is there any reason not to use the bitwise operators &, |, and ^ for "bool" values in C++? ”
Yes, the logical operators, that is the built-in high level boolean operators !, && and ||, offer the following advantages:
Guaranteed conversion of arguments to bool, i.e. to 0 and 1 ordinal value.
Guaranteed short circuit evaluation where expression evaluation stops as soon as the final result is known.
This can be interpreted as a tree-value logic, with True, False and Indeterminate.
Readable textual equivalents not, and and or, even if I don't use them myself.
As reader Antimony notes in a comment also the bitlevel operators have alternative tokens, namely bitand, bitor, xor and compl, but in my opinion these are less readable than and, or and not.
Simply put, each such advantage of the high level operators is a disadvantage of the bitlevel operators.
In particular, since the bitwise operators lack argument conversion to 0/1 you get e.g. 1 & 2 → 0, while 1 && 2 → true. Also ^, bitwise exclusive or, can misbehave in this way. Regarded as boolean values 1 and 2 are the same, namely true, but regarded as bitpatterns they're different.
How to express logical either/or in C++.
You then provide a bit of background for the question,
“I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression.”
Well, the bitwise operators have higher precedence than the logical operators. This means in particular that in a mixed expression such as
a && b ^ c
you get the perhaps unexpected result a && (b ^ c).
Instead write just
(a && b) != c
expressing more concisely what you mean.
For the multiple argument either/or there is no C++ operator that does the job. For example, if you write a ^ b ^ c than that is not an expression that says “either a, b or c is true“. Instead it says, “An odd number of a, b and c are true“, which might be 1 of them or all 3…
To express the general either/or when a, b and c are of type bool, just write
(a + b + c) == 1
or, with non-bool arguments, convert them to bool:
(!!a + !!b + !!c) == 1
Using &= to accumulate boolean results.
You further elaborate,
“I also need to accumulate Boolean values sometimes, and &= and |=? can be quite useful.”
Well, this corresponds to checking whether respectively all or any condition is satisfied, and de Morgan’s law tells you how to go from one to the other. I.e. you only need one of them. You could in principle use *= as a &&=-operator (for as good old George Boole discovered, logical AND can very easily be expressed as multiplication), but I think that that would perplex and perhaps mislead maintainers of the code.
Consider also:
struct Bool
{
bool value;
void operator&=( bool const v ) { value = value && v; }
operator bool() const { return value; }
};
#include <iostream>
int main()
{
using namespace std;
Bool a = {true};
a &= true || false;
a &= 1234;
cout << boolalpha << a << endl;
bool b = {true};
b &= true || false;
b &= 1234;
cout << boolalpha << b << endl;
}
Output with Visual C++ 11.0 and g++ 4.7.1:
true
false
The reason for the difference in results is that the bitlevel &= does not provide a conversion to bool of its right hand side argument.
So, which of these results do you desire for your use of &=?
If the former, true, then better define an operator (e.g. as above) or named function, or use an explicit conversion of the right hand side expression, or write the update in full.
Contrary to Patrick's answer, C++ has no ^^ operator for performing a short-circuiting exclusive or. If you think about it for a second, having a ^^ operator wouldn't make sense anyway: with exclusive or, the result always depends on both operands. However, Patrick's warning about non-bool "Boolean" types holds equally well when comparing 1 & 2 to 1 && 2. One classic example of this is the Windows GetMessage() function, which returns a tri-state BOOL: nonzero, 0, or -1.
Using & instead of && and | instead of || is not an uncommon typo, so if you are deliberately doing it, it deserves a comment saying why.
Patrick made good points, and I'm not going to repeat them. However might I suggest reducing 'if' statements to readable english wherever possible by using well-named boolean vars.For example, and this is using boolean operators but you could equally use bitwise and name the bools appropriately:
bool onlyAIsTrue = (a && !b); // you could use bitwise XOR here
bool onlyBIsTrue = (b && !a); // and not need this second line
if (onlyAIsTrue || onlyBIsTrue)
{
.. stuff ..
}
You might think that using a boolean seems unnecessary, but it helps with two main things:
Your code is easier to understand because the intermediate boolean for the 'if' condition makes the intention of the condition more explicit.
If you are using non-standard or unexpected code, such as bitwise operators on boolean values, people can much more easily see why you've done this.
EDIT: You didnt explicitly say you wanted the conditionals for 'if' statements (although this seems most likely), that was my assumption. But my suggestion of an intermediate boolean value still stands.
Using bitwise operations for bool helps save unnecessary branch prediction logic by the processor, resulting from a 'cmp' instruction brought in by logical operations.
Replacing the logical with bitwise operations (where all operands are bool) generates more efficient code offering the same result. The efficiency ideally should outweigh all the short-circuit benefits that can be leveraged in the ordering using logical operations.
This can make code a bit un-readable albeit the programmer should comment it with reasons why it was done so.
IIRC, many C++ compilers will warn when attempting to cast the result of a bitwise operation as a bool. You would have to use a type cast to make the compiler happy.
Using a bitwise operation in an if expression would serve the same criticism, though perhaps not by the compiler. Any non-zero value is considered true, so something like "if (7 & 3)" will be true. This behavior may be acceptable in Perl, but C/C++ are very explicit languages. I think the Spock eyebrow is due diligence. :) I would append "== 0" or "!= 0" to make it perfectly clear what your objective was.
But anyway, it sounds like a personal preference. I would run the code through lint or similar tool and see if it also thinks it's an unwise strategy. Personally, it reads like a coding mistake.