Problems with "string" variables

Hello,
I have problems with "string" variables.

I want to write a text on a string variable in my code.
The problem is that the text is reset with every new beginning of the "void loop".

I think that I have a mistake in thinking.
I would be very happy about answers!

Many Thanks!!!

Here is some example code:

String mystring = "Hello";

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

void loop() {
  Serial.println(mystring); // first run:"Hello"; second pass, ALSO:"Hello"
    
  String mystring = "world";
  
  Serial.println(mystring); // first run:"world"; second pass:"world"

  delay(200);
  }

I want both to have variables "world" on the second run.

Suppose that loop() has executed 3 times. What do you want printed ?

Read about variable scope

You have two mystring variables, a global and a local one

I want the following to be output.

Hello
world
world
world
world
world

did you read the link about "scope" ?

do you understand why your code is wrong?

Thanks for your answer. I looked at the link. But not not understood.

can you explain to me why the string is being reset. and what can I do about it?

Thanks for your answer!

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

change

String mystring = "world";

to

mystring = "world";
1 Like

Many thanks for your help !

Thank you "J-M-L" for your explanation. I understand it. Thank you so much!

Thank you "killzone_kid" your idea worked.
Thank-you!

If you are using Arduino Strings check out my tutorial on
Taming Arduino Strings

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