Question

I am reading this code in C++ http://ajmarin.alwaysdata.net/codes/problems/952/ and I don't understand what this &= in the code does:

int k = 5;
int ts = 5;
bool possible = true;

And it have this line:

if(!(possible &= k == ts)) 
    break;

I want to know what is the meaning of "&=" I am new in C++ language and I've never seen something like this for example in java, or at least I don't know the meaning.

The right hand of the statement returns "1" due to the fact that ( k == ts ) that is ( 5 == 5) but the left hand ( possible &= k ) don't know the meaning..

Thank you

Was it helpful?

Solution 3

&= is Bitwise AND assigning the result to the lhs( a&=b => a=a&b). (like +=)

It will perform a logical AND and assign the result to possible.


Due to Operator precedence the expression will be like: possible &= (k == ts).

Which means that it will evaulate (k == ts) resulting in a boolean, make a logical and with possible, store it in possible and return it as a result.

OTHER TIPS

It's equivalent to:

possible &= (k == ts);
if (! possible)

and is further equivalent to

possible = possible & (k == ts);
if (! possible)

Here, & is the bitwise AND. num & 0 will always gives you 0 while num & 1 will give you 1 if the least significant bit of num is 1 or 0 otherwise.

To read on, check out

It is a bitwise-AND-assignment, which is a Compound Assignment Operator. It is equivalent to the following statement:

possible = possible & (k == ts);
if(!possible)
    ....

Note that your original code-style is considered by many to be an anti-pattern, and you should in general avoid assignments in if statements (e.g. here and here).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top