0

I modify this code from my friend and it look strange.

void setup() {
    Serial.begin(115200);
    Serial.println("reset");
}
void loop() {
    for (int d; d <= 32767; d++) {
      Serial.println(d);
      delay (1000);
    }
}

for some reason when you press reset, the variable will keep counting from last value as shown.

enter image description here

this not gonna happen when you put these block in setup()

I know that not good idea to use varible in for loop without assigned the value, but I belived it must have a interesting reason for this. For my hypothesis, the variable value just allocate with same address in memory. when this code run in setup() some how the complier detect this situation and assign 0 as initial value. but when in the loop() some how the compiler don't assign new value to the memory address and it get old value from last time the program was run before resetted. I still need further explanation.

2
  • This code behaves normally for me - 'd' starts at 0 for every reset. Is this the complete and exact code that made the output example?
    – JRobert
    Apr 18, 2021 at 14:41
  • @JRobert, yes I use Arduino UNO with Arduino 1.1.13
    – M lab
    Apr 18, 2021 at 14:43

1 Answer 1

3

I think you missed a compiler warning (I did, too!) - notice that you are using 'd' uninitialized. On each re-entry to the loop() function, loop()'s stack will be in the same place in memory. The for-loop doesn't initialize 'd', but the boot loader did zero RAM for your first run. 'd' happens to occupy the same memory location on each entry to loop(), so the old value (just before reset) is still in place. Since the for-loop didn't re-initialize it... :)

The fix is:

for (int d=0; d <= 32767; d++) {

Update:

That begs the question: Why did your run fail as expected, while my run appeared to execute normally? My guess is different bootloaders, one that does, and one that doesn't, initialize SRAM on a reset that doesn't result in an upload.

3
  • Wow, never think that was firmware problem. I doesn't need the fix I want the explanation.
    – M lab
    Apr 18, 2021 at 18:55
  • I can't confirm that the difference between your runs and mine is due to firmware, but there's no question that 'd' was being used without initialization.
    – JRobert
    Apr 18, 2021 at 19:03
  • old IDE, old AVR toolchain
    – Juraj
    Apr 19, 2021 at 6:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.