X=y=z doesn't return error

image
I was making a simple project, when I mistyped the code and ended with this. What does it do? Why doesn’t it return an error? Why is ON underlined in yellow? Doesn’t it change? Or is it because it is not used later in the code?

Anyway, I am confused. Can somebody please explain?

Hello,

See:
Operator Precedence < See Associativity

Associativity.

When an expression has two operators with the same precedence, the expression is evaluated according to its associativity . For example x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three variables with the value 17, since the = operator has right-to-left associativity (and an assignment statement evaluates to the value on the right hand side).

I did not get an underline:

boolean test [][] = new boolean [2][2];

void setup() 
	{
  //int i = 0;
  //int j = 0;
  //boolean on = test[i][j] = random(1)<0.5;
  
  for(int i = 0; i<2; i++) for(int j = 0; j<2; j++) {
    boolean on = test[i][j] = random(1)<0.5;
    println (on);
    }
  }

Variable Scope / Examples / Processing.org

:)

1 Like

In some programming languages, the assignment command returns the value that was assigned. This can be useful if you want to assign several variables to the same value at the same time.

Thus,

x = y = z;

Is the same as

y = z;
x = y;

You should experiment with this in your language of choice.

4 Likes

I wouldn’t say some. Apart from Python, I’d say in mostly C-derived languages we can have assignments almost anywhere.

BtW, the assignment symbol isn’t a command but an operator (except Python):

B/c it’s an operator, we can use it not only in chainable assignments like in here:
studio.ProcessingTogether.com/sp/pad/export/ro.9lMOG-RZX8JDk

final float x = points[i].x += EASE * .5 * xdist;
final float y = points[i].y += EASE * .5 * ydist;

But also as a conditional test in if () blocks:
studio.ProcessingTogether.com/sp/pad/export/ro.9V7R1wu55fOiN

if ( isDead = isHit() )  --aliveNum;
void update() {
  if ( (x += vx) < rw | x > width  - rw )  vx *= -1;
  if ( (y += vy) < rh | y > height - rh )  vy *= -1;
}

We can even invoke the value assigned as a function and pass it as an argument afterwards:

Knot(final PVector vec) {
  c = color((v = vec).mag(), 255, 255);
}

P.S.: Chain-assignments are evaluated from right to left btW.

2 Likes