kentor
kentor

Reputation: 18524

Multiple assignments in one line

I got a task to rewrite C# code in NodeJs. Unfortunately there are some nasty oneliners in that function which I do not fully understand.

Code

int b, sign = ((b = byteBuffer.ReadByte()) >> 6) & 1, i = b & 0x3F, offset = 6;

Question

I can see that there are multiple assignments, but I am not sure what values these variables are supposed to have.

Could someone explain this oneliner and/or rewrite it into a simpler to understand C# snippet?

Upvotes: 1

Views: 250

Answers (1)

quetzalcoatl
quetzalcoatl

Reputation: 33536

Basically, it's the same as

int b = byteBuffer.ReadByte();
int sign = (b >> 6) & 1;
int i = b & 0x3F;
int offset = 6;

In detail:

In the original line, each top-level , splits the declaration:

int b, sign = ((b = byteBuffer.ReadByte()) >> 6) & 1, i = b & 0x3F, offset = 6;
     ^here                                          ^here         ^ here

and then you're left with a tricky :

int b;
int sign = ((b = byteBuffer.ReadByte()) >> 6) & 1;
// ...

which in fact first defines B as without initial value, but then the next expression immediatelly assigns the result of 'ReadByte' to the B as the first sub-operation, so in fact it's the same as initializing B with it from the start, and you end up with what I wrote in the first code snippet.

Upvotes: 4

Related Questions