9

Can someone explain the following piece of code

int x = 45; 
int y = x &= 34;

It assigns 32 to y

1
  • Probably accidental rollback by OP Commented May 17, 2010 at 9:04

7 Answers 7

25

It's performing a bitwise "and" as a compound assignment operator. It's equivalent to:

int x = 45;
x = x & 34;
int y = x;

Now 45 = 32 + 8 + 4 + 1, and 34 = 32 + 2, so the result of a bitwise "and" is 32.

Personally I think that using a compound assignment operator in a variable declaration is pretty unreadable - but presumably this wasn't "real" code to start with...

Sign up to request clarification or add additional context in comments.

1 Comment

Dammit, you can't compete with the Skeet! (needs to be added here: meta.stackexchange.com/questions/9134/jon-skeet-facts). When 10 people including @Jon answer a question simultaneously, only he will walk away with 2+ Nice Answer badges.... and all before morning tea time (in London time). Nice :)
10
int x = 45; 
int y = x &= 34;
Gives: y = 32

int x = 45;  // 45 = 101101
             // 34 = 100010
x = x & 34;  // 101101
             // 100010 &
             // --------
             // 100000  ( = 32 )

int y = x;    //  y = 32

Comments

0

It's a bitwise operation, more information can be found here:

http://msdn.microsoft.com/en-us/library/sbf85k1c%28VS.80%29.aspx

Comments

0

It is equivalent to:

int x = 45;
x = x & 34;
int y = x;

The & operator for integral types computes the logical bitwise AND of its operands.

Comments

0

Looks like a bitwise AND, which is assigned to x by the &= shortcut notation, and is also assigned to y.

Comments

0

Here x &= 34 is used both as an assignment and an expression. It calculates the value of x & 34, assigns it to x, and the value of the expression is what's assigned.

The result of the bitwise and operation 45 & 34 is 32, which is assigned to x, and then also to y.

Comments

0
45 = 101101(binary)
34 = 100010(binary)

45 & 34 = 100000(binary) = 32

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.