Switch Cases in RobotC

Hey, i was wondering if someone could point me to a video or explain to me the concept and practical use of switch cases over if statements. Thank you.

Here is an example using switch case.

It really makes the most sense when you expect to have more than 2 cases. The variable your comparing doesn’t have to be written in every if statement.

Here’s a short video. It explains the logic of it fairly well.

As for why you would use switch statements over if statements, it’s generally to avoid situations like this.

Ouch, that’s painful to look at.

1 Like

oof ouchie owie

It makes it so that you don’t have to type nearly as much, thus you have a smaller file size and your program is easier to understand.

Can someone confirm smaller file sizes? AFAIK it is the same length in machine language, because it functions exactly the same way.

Okay, so I guess the file size on the computer is smaller, but I mean on the cortex.

Ya he was only talking about the c file not the compiled byte code.

Compiled size and speed will depend very much on the type of switch statement, how many choices, are they sequential or a spread out. We did some analysis several months ago of the following code that may interest you.

Functionality of this code

 if ((XX == 1) || (XX == 2) || (XX == 3) || (XX == 4))
    X += 1;

and this code

  switch (XX)
  case 1:
  case 2:
  case 3:
  case 4:
    X += 1;

is the same

However, the switch version is around (theoretically) 6 times faster.

Neat, I am very happy to have found out about switch statements this season. They are very helpful.