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?
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;
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