Cant find the logic about this failure

Hello,

Im trying a very simple sketch but can't understand the logic behind this failure:

If I execute:

const int nav = 8 ;
String selecopt = "Default";
long previousMillis = 0;

void setup()
{
Serial.begin(9600);
   pinMode(nav, INPUT);
   pinMode(13, OUTPUT);
 }

void loop () {  
if(digitalRead(nav) == HIGH) { String selecopt = "Cmon" ; digitalWrite(13, HIGH);  }

if ( (millis() - previousMillis > 1000)) { previousMillis = millis(); Serial.println(selecopt);  }
 }

When I press the button, the led goes light but serial monitor wont show me "Cmon" but just "Default", no matter how many times i hit digital input on pin 13.

But if I run the code:

const int nav = 8 ;
String selecopt = "Default";
long previousMillis = 0;

void setup()
{
Serial.begin(9600);
   pinMode(nav, INPUT);
   pinMode(13, OUTPUT);
 }

void loop () {  
if(digitalRead(nav) == HIGH) {  digitalWrite(13, HIGH);  }
String selecopt = "Cmon" ;
if ( (millis() - previousMillis > 1000)) { previousMillis = millis(); Serial.println(selecopt);  }
 }

"Cmon" is the only thing that is show on serial monitor, naturally.

Why it doesnt work inside the IF statement as led does?
What am I missing here?

Appreciate any clue.

Rodrigo

String selecopt = "Default";

Here you have a global variable.

{ String selecopt = "Cmon" ; digitalWrite(13, HIGH);  }

Those open and close curly braces define the scope of the selecopt (local) variable. It ceases to exist after the }, so the global (unmodified) variable is now accessible.

Try losing the String variable declaration in the if block. Then, the global variable will be modified.

Thanks PaulS to bring some logic to the problem. So if I redeclare the string under main loop section it works, otherwise it doesnt.

How to lose the string variable and redeclare inside the IF statement?

Edited ====
I mean: I like to redeclare the global variable inside the IF statement
Edited ====

Thanks,
Rodrigo

How to lose the string variable and redeclare inside the IF statement?

{ selecopt = "Cmon" ; digitalWrite(13, HIGH);  }

Just delete the word String. It's presence is what is causing the creating of a local variable with the same name as the global variable.

Ahhh great.... thank you.
Weird because its just the usual way to redeclare variables.
It's me just trying String for the first time and I may be mind blocked or something.

Thanks PaulS