Minification question

The following code cycles the value of the variable NET within a range of 0 to 4.

int NET;
void setup() {
  println(NET);
}
void draw() {
}
void keyPressed() {
  if (keyCode == UP || keyCode == DOWN) NET = ((NET += keyCode == UP ? 1 : -1) < 0 || NET > 4) ? NET - 5 * NET/abs(NET) : NET;
  println(NET);
}

My question is, why doesn’t the following work? In theory, I could substitute the outermost assignment with a -= operator:

void keyPressed() {
  if (keyCode == UP || keyCode == DOWN) NET -= ((NET += keyCode == UP ? 1 : -1) < 0 || NET > 4) ? 5 * NET/abs(NET) : 0;
}

In this case, pressing the respective buttons just makes the variable switch between 0 and 5. In other words, it totally breaks. Is there perhaps an issue with the two assignment operators colliding somehow?

is there really a reason you need to keep this to a single line? as you know it’s just making it complicated to the point you can’t understand the code. isn’t it much better to KISS and minify elsewhere

void keyPressed() {
  if(keyCode == UP) {    
    NET = NET + 1 > 4 ? 0 : NET + 1;
  }
  else if(keyCode == DOWN) {
    NET = NET - 1 < 0 ? 4 : NET - 1;
  }
  println(NET);
}

i don’t see what is wrong with the above code. it does the job and i wouldn’t call it bulky it is clean and understandable.

2 Likes

So, you don’t understand why it’s not working?

i think it’s because you are doing assignment and comparison. still i think it is not a nice way to do things but that’s just my opinion.

1 Like

Always put readability and maintainability over shortness of code.

You could even move the 2 sections into separate functions

While I applaud the effort to understand the intricacies of the language and/or compiler, you can greatly simplify your code using the % modulus operator:

if( keyCode == UP || keyCode == DOWN )
    NET = (NET + (keyCode == UP ? 1 : 4)) % 5;

% on a negative gives a negative which is why I add 4 rather than subtracting 1.

As to your actual question, if you want to tease out what the compiler is doing, try building up to your expression incrementally from simpler components to see where it’s failing to give the result you expect.

Thanks for that. Also, I did build it step by step, and it seems to fail the moment I introduce two increment operations. I don’t know why though.