Switch case format - is comma the equivalent of semicolon??

Hi,

I have come across this switch case where the use of comma instead of semicolon yields the same result??
My questions:

  1. Why doesn't the Arduino IDE 1.8.9 complain about this?
  2. How come a comma works?
switch(val)             //switch statement
    {
      case 'F': front=speed+0.05; BTSerial.println("Foward");break;
      case 'S': slow=speed-0.05; BTSerial.println("Slow");break;
    }

And this is seemingly the equivalent with a comma before BTSerial.println:

switch(val)             //switch statement
    {
      case 'F': front=speed+0.05, BTSerial.println("Foward");break;
      case 'S': slow=speed-0.05, BTSerial.println("Slow");break;
    }

I tested both and got the same output on my serial monitor.

Try printing the value of front and slow using both forms of code. Are the values what you expect ?

Welcome to the wonderful world of the comma operator

comma operator

I won't pretend to understand the nuances but, a comma can be a separator *or *an operator. A discussion at stack overflow.

It’s not a syntax error because both statements are expression statements. In many such cases it doesn’t change the result but it is bad practice and can create some mysterious errors.

About the only time one normally sees the comma operator used is in a ‘for’ loop where more than one variable is incremented:

  for (int i = 0, j = 1; i < 20; i = i+1, j = j << 1)

Since you can put only one ‘expression’ in the increment part of the loop, the comma allows two expressions to go in that one place.

So, i guess i should play it safe and go with the semicolon instead.

But is the following correct or do i need to group all the statements under each case between braces?

switch(expression)
{
 case value1:
   statement 1;
   statement 2;
   statement 3;
   break;
case value2:
   statement 1;
   statement 2;
   statement 3;
   break;
}

Like, this?

switch(expression)
{
  case value1:
    {
    statement 1;
    statement 2;
    statement 3;
    break;
    }
 case value2:
    {
    statement 1;
    statement 2;
    statement 3;
    break;
    }
}

Both ways are fine, the braces are normally left out.

If you need to declare a local variable inside a case statement, you must use the braces to create a local scope. One of those other intricacies of C++...