Problem member function returning wrong value.

Hi! I've a problem, the member function doesn't return the same value than the value computed in the main function.

I want to perform bitwise operators between booleans like this :


When I do it on the main function it's ok. (a ^ b ^ r) returns 0 so it's correct.

int main(int argc, char* argv[])
{
bool a = 1;
bool b = 1;
bool r = 0;
BigInt test;
std::cout<<"sum = "<<(a ^ b ^ r)<<std::endl;
std::cout<<"ret = "<<r<<std::endl;
return 0;
}

But when I do this in a member function, the value returned by the member function is not correct. (It returns 1 instead of 0)

class BigInt {
public:
bool addBits(bool a, bool b, bool& r) {
r = (a & b) | (a & r) | (b & r);
return (a ^ b ^ r);
}
};
int main(int argc, char* argv[])
{
bool a = 1;
bool b = 1;
bool r = 0;
BigInt test;
std::cout<<"sum = "<<test.addBits(a, b, r)<<std::endl;
std::cout<<"ret = "<<r<<std::endl;
return 0;
}

Why ? I'm using gcc-4.9 on ubuntu 18.04, I understand now why sometimes I have invalid variable adresses and display bugs if even a simple source code doesn't runs well.
Last edited on
Do you realize that your first snippet and second snippet are not working with the same formula?

In the non-class snippet r is always zero. In the second snippet r is a computed value not equal to zero.

Erf so stupid I'm, I computed r before computing a ^ b ^ r so this is why it returned me the wrong value.
solved
Registered users can post here. Sign in or register to post.