Go Down

Topic: char table in a function retains values between calls without static [SOLVED] (Read 285 times) previous topic - next topic

jbellavance

Hi,

If you take a look at the code below, it works perfectly, even if buff[] is not declared static.

Why?
Code: [Select]

bool table[3][3] = {false, false, false,
                    false, false, false,
                    false, false, false};

bool readMonitor() {
  char buf[3];
  static byte i = 0;
  if (Serial.available()>0){ buf[i] = Serial.read(); i++; }
  if (int(buf[i-1]) == 13) {
    i = 0;
    table[buf[0]-48][buf[1]-48] = true;
    return true;
  }
  return false;
}


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

void loop() {
  if (readMonitor()) {
    for (int i = 0 ; i < 3 ; i++) {
      for (int j = 0 ; j < 3 ; j++) Serial.print(table[i][j]);
      Serial.println();
    }
    Serial.println();
  }
}
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

AWOL

You got lucky.

Ever hear the phrase "works like a charm" ?

How often do charms work?
Would you rely on that?

gfvalvo

The stack locations where buff[] is stored just don't happen to be overwritten by other code.
No technical questions via PM. They will be ignored. Post your questions in the forum so that all may learn.

jbellavance

Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

Go Up