Problems with "string" variables

when you do
String mystring = "Hello";
you declare and define a GLOBAL variable named mystring, initialized with the content Hello

This variable's lifetime is the one of the whole program as it's a global variable and it's visible everywhere (read scope, practice )

when you do this in the loop
String mystring = "world";
you declare and define the LOCAL variable named ASLO mystring initialized with the content world

this LOCAL variable - from there on - in the loop() function will hide the GLOBAL variable of the same name (which content has not changed, it's still Hello)

so

  Serial.println(mystring); // ==> PRINT THE GLOBAL VARIABLE
    
  String mystring = "world";
  
  Serial.println(mystring); //  ==> PRINT THE LOCAL VARIABLE

if you don't want the local variable, don't re-declare a variable... just assign the new value (don't declare!)

String mystring = "Hello";

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

void loop() {
  Serial.println(mystring);  // ==> FIRST RUN WILL PRINT THE INITIAL VALUE OF THE GLOBAL VARIABLE
  mystring = "world";        // ==> ASSIGN A NEW VALUE TO THE GLOBAL VARIABLE
  Serial.println(mystring);  // PRINT THE MODIFIED CONTENT
  delay(200);
}
1 Like