Int Loop - Noob Question

OK so this feels like a silly question but Google isnt helping (most likely because I'm searching the wrong thing) :cold_sweat:

If I declare a value to an int during my sketch should it clear itself when it starts the void loop again? If that's correct is there a way to store the value when it does repeat again.

int myvar = 1;
// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(57600);
int myvar = 2;
Serial.println(myvar);
}

// the loop routine runs over and over again forever:
void loop() {
  
Serial.println(myvar);
  delay(1000);        // delay in between reads for stability
int myvar = 3;
Serial.println(myvar); 
  delay(1000);        // delay in between reads for stability
}

Therefore the serial monitor reads 1 2 1 3 1 3 1 3 etc
But I want it to read 1 2 3 3 3 3 3 3 etc

Sorry for such a dumb question...

Globals are only initialized (by default to zero) once at initialization time, before setup() is called.

If you want to reinitialize a variable at the top of the loop() function, just assign it yourself in the usual way.

-br

You need to have a look at the scope of the variables.
At the top you have int myvar=1
This creates a global variable, myvar, and assigns it to 1.
In setup you then create another variable, which also happens to be called myvar, and initialise it to 2.
Then finally in your loop, the first thing you do is print myvar, this is scoped globally, you haven't created any variable called myvar locally, next you've created another variable myvar, and initialised it to 3.
What you should do instead is in your setup and loop function use this syntax:

myvar=2;

This way myvar will refer to the globally scoped variable, and not a locally created one.

Hope this helps,

tobyb121