1

I am trying to rewrite a piece of C code from another author into Python, and I came across the following type of notation:

x = y[a=b];

where y is an array and a and b are integers. At first I thought it meant something like this:

a = b;
x = y[a];

But apparently it doesn't. Can anyone tell me what this expression means? Forgive me if this question is a duplicate, but it is very hard to summarise this question in a couple of searchable keywords, and I could not find anything that answers my question.

The source of the code I am trying to rewrite: link

EDIT:

The Python-rewritten code does not work as it should (stuck in a loop), so I thought that I misinterpreted the above statement. But as several of you have suggested, it was correct in the first place. I must be something else then...

MPA
  • 1,878
  • 2
  • 26
  • 51

2 Answers2

7
x = y[a=b];

and

a = b;
x = y[a];

are equivalent. The expression a=b has the value of the left operand after assignment.

http://msdn.microsoft.com/en-us/library/474dd6e2.aspx

QuestionC
  • 10,006
  • 4
  • 26
  • 44
  • 1
    Don't you mean "the left hand operand", or "the left hand side of the operator"? `a` and `b` are the operands, `=` is the operator. – Michael Dorst Aug 14 '14 at 14:44
  • Thank you for your answer and reference. Although my code still isn't working, at least I now know that the interpretation of `y[a=b]` was not the problem. – MPA Aug 14 '14 at 17:31
  • Let me just add, this actually comes up in C a *lot*, though not in the weird way that you are using it. `while ((ch = getchar()) != EOF)` is idiomatic. – QuestionC Aug 14 '14 at 18:03
3

I think you are actually right, it means:

a = b;
x = y[a];

a = b itself returns b after assigning b to a. Therefore y[a=b] will return y[b] but also assigned b into a.

EDIT

in your comment you say, "if a = 1 and b = 3, then it resolves to y[3] with a = 3 and b = 3".

This is exactly what the code above does:

At the beginning, a is equal to 1 and b is equal to 3.

a = b;

Now a contains 3 and b still contains 3.

x = y[a];

Now x has been assigned the value in y[3], a still contains 3 and b still contains 3.

Community
  • 1
  • 1
BlueTrin
  • 9,610
  • 12
  • 49
  • 78