Skip to content

Multiple variable declaration/assigment in C switch() statement yield an error in the executable #11639

Closed
@Harm-Paas

Description

@Harm-Paas
/* --------------------------------------------------------------------------
 * Arduino compiler error :
 *  Multiple inline variable declarations/assigments in a C switch statement
 *  yield an error in the executable.
 *  After multiple variable declarations in the switch() construct
 *  the rest of the switch statement case entries become unreachable.
 * 
 * Compiler version : Arduino IDE 1.8.15
 * O.S. Windows10
 *
 * 2021-07-25 Harm Paas PA0HPG
 */

void pickchoice(char MyChoice) {
   char Cmd ;

   Cmd = MyChoice;
   
   switch(Cmd) {
   case 'A':
     int var1 = 1;        // Signed variables in switch() 
     Serial.println(var1);
     //...stmts...
   break;
   case 'B':
     int var2 = 2;
     Serial.println(var2);
   // ...stmts...
   break;
   case 'C':
     int var3 = 3;
     Serial.println(var3);
     // ...stmts...
   break;
   } // end switch
}
//   -----------------------------------------------------------------------
//   Correct version of the same function:
void correctpickchoice(char MyChoice) {
   char Cmd ;
   int var1 = 10 ; // Do not declare/assign variables in the switch
   int var2 = 20 ;
   int var3 = 30 ; 

   Cmd = MyChoice;
   
   switch(Cmd) {
   case 'A':
     var1 = 10;
     Serial.println(var1);
     //...stmts...
   break;
   case 'B':
     var2 = 20;
     Serial.println(var2);
     // ...stmts...
   break;
   case 'C':
     var3 = 30;
     Serial.println(var3);
   // ...stmts...
   break;
   } // end switch
}
//   -----------------------------------------------------------------------

void setup(){
  Serial.begin(9600);
}

void loop() {

  Serial.println("Executable error with multiple variable declarations in switch()");
  Serial.println("Wrong version:");
  pickchoice('A');
  pickchoice('B');
  pickchoice('C');

  Serial.println("Corrected version of the declaration :");
  
  correctpickchoice('A');
  correctpickchoice('B');
  correctpickchoice('C');

  while(true);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions