Switch case and local variables question

In a program I discovered the same local variable being declared in very "case" of a switch, and not giving compile errors (such as "redefinintion of a variable").
I feel this is not a good way of using this local variable but I would like some expert opinion on this?

void loop()
{
.....
  switch (keyStroke)
  {
   case 'A':
    {
      bool caseReady = false;
      ...
     }
    case 'B':
     {
      bool caseReady = false;
      ....
      }
    ....
   }
 ....
}

You should know what you are doing .

which means if the variable should only be usable/visible inside a certain case of the switch-case-break-statement then you can write code like this.

In a lot of aplications / codes most variables are used in a wider area than just a single

case 'B':

etc.
especcially if you use the same name in different case: this might be confusing

if you look very close

case 'B':
     { // << opening curly brace
      bool caseReady = false;
      ....
      } // << closing curly brace
    ....

the curly braces tell the compiler the things between this opening and closing curly brace
is a separate section. Which means declarations inside this braces are only valid inside this braces.
declaration is something different than assigning a value

declaration: variable-type variable-name
bool myBoolVar;
.
.
.
assigning variable-name = value
myBoolVar = true
.
.
.
In the declaration you can add assigning an initial value
declaration with initial assigning: variable-type variable-name = value
bool myBoolVar = false;

best regards Stefan

1 Like

If you use the variable inside the single case block only - it is perfectly normal.

You just need to study "variable scope" concept, to understand you aren't redefine a variable, but a new local variable that "hides" the other one.

It's the braces. Braces define scope. If you took the braces off of the cases then it would give a compile error.

Consider this to see how scoping works with braces. I've scoped a global, a variable local to loop, and a variable local to the if statements all with the same name. Pin 2 is tied HIGH.

int name = 1;

void setup() {
  Serial.begin(115200);

  Serial.print("In setup ");
  Serial.println(name);

  pinMode(2, INPUT);  // I need something so the compiler doesn't optimize away my if statement. 

}

void loop() {
  
  int name = 2;

  if(digitalRead(2) == HIGH){
    int name = 3;
    Serial.print("In if statement ");
    Serial.println(name);
  }  
  if(digitalRead(2) == HIGH){
    int name = 4;
    Serial.print("In if statement ");
    Serial.println(name);
  }  
  Serial.print("Outside if Statement ");
  Serial.println(name);

  function();

  while(1);
}


void function(){
  Serial.print("In function call ");
  Serial.println(name);
}

OUTPUT:

In setup 1
In if statement 3
In if statement 4
Outside if Statement 2
In function call 1

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.