Why is my code adding but not subtracting?

Hi,

I am trying to get my Arduino to do some really simple addition and subtraction of some variables.

The addition works fine, but the subtraction does not. The value stays the same?

int x = 65;
int y = 65;

case UP_KEY:
y = y - 1;
case DOWN_KEY:
y = y + 1;
case LEFT_KEY:
x = x - 1;
case RIGHT_KEY:
x = x + 1;

Any ideas what is going on?

Ta.

What happens is this:

Every time you check this switch, you end up incrementing AND decrementing the value, BUT the increment will work because the switch will jump straight to that case [skipping the decrement].
Lousy explanation, a bit late here.

Try this code:

switch ( key ){
  case UP_KEY:
    y = y - 1;
    break;   
  case DOWN_KEY: 
    y = y + 1;
    break;   
  case LEFT_KEY:
    x = x - 1;
    break;   
  case RIGHT_KEY:
    x = x + 1; 
    break;   
}

:slight_smile:

^

Awesome, Thanks!

Lousy explanation, a bit late here.

Actually the OP's listing and problem description along with your explanation and correction is the best example I've seen of a common pit fall of using the case function. Good examples are the best teaching tools.

The case function is a nice looking structure that seems clear and simple but C being C can always find a was to bite you in the butt.

Thanks for your contribution.

Lefty