Reputation: 1243
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
Upvotes: 1
Views: 3763
Reputation: 241671
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)!
notUpvotes: 2
Reputation: 72271
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;
Upvotes: 4