DELETE me
DELETE me

Reputation:

How does this C# code snippet work?

Can someone explain the following piece of code

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

It assigns 32 to y

Upvotes: 9

Views: 411

Answers (7)

hakan
hakan

Reputation: 906

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

45 & 34 = 100000(binary) = 32

Upvotes: 0

Bastiaan Linders
Bastiaan Linders

Reputation: 2141

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

Upvotes: 10

Guffa
Guffa

Reputation: 700730

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.

Upvotes: 0

slugster
slugster

Reputation: 49985

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

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039418

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.

Upvotes: 0

Hans Olsson
Hans Olsson

Reputation: 55049

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

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

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503290

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...

Upvotes: 25

Related Questions