-4

Why doesn't the two different declarations of the variable 't' within the same function cause a conflicting declaration error? (Because it doesn't). Can this way of using the same name for a variable be used safely?

The function hloop() is run as a task with scheduler. I am running an ESP32 working with the Arduino IDE.

void hLoop(void * param) {
  time_t startR = NULL;
  bool Ok = true;

  for (;;) {

      preferences.begin("conf", true);
      String silent = preferences.getString("silentS", "07:00:00");
      preferences.end();

      struct tm t;     //  **<-------------- HERE -----------**
      strptime(silent.c_str(), "%H:%M:%S", &t);

      if (t.tm_hour == info->tm_hour) {
        silentM = 1;
      }

      preferences.begin("conf", true);
      silent = preferences.getString("silentE", "19:00:00");
      preferences.end();

      strptime(silent.c_str(), "%H:%M:%S", &t);

      if (t.tm_hour == info->tm_hour) {
        silentM = 0;
      }

      if (f.get() == 0 ) {
        if (startR == 0) {
          startR = time(NULL);
        }

        time_t t = time(NULL);   //  **<-------------- AND HERE -----------**
        double diff = difftime(t, startR);

        if (diff > 1800) {
          setN();
          Ok = false;
        }
      } else {
        startR = NULL;
        Ok = true;
      }
  }
}

I would have expected a conflicting declaration error in compilation.

I did try to add another conflicting declaration in the code, similar to this


int i=0;
i++;
Serial.print(i);

char i[]="Hello";
Serial.print(i);

within the function above, and then I did get a conflicting declaration error. So why not with the t?

3
  • 3
    In what language? Commented May 21, 2024 at 11:33
  • 1
    That second t is in an if block. Different scope. Commented May 21, 2024 at 12:43
  • 1
    Look up "C++ variable shadowing" - see for example here: learncpp.com/cpp-tutorial/variable-shadowing-name-hiding Commented May 21, 2024 at 12:53

1 Answer 1

0

It only works in this case, because the variables are declared in different scopes. The second declaration is only valid/accessable within the "if (f.get() == 0 ) {..."-condition. When accessing "t", the declaration in the nearest/latest scope will be used. (the first declared "t" will not be accessable inside that scope)

if you try to declare both variables in the same scope, you will get a conflict-error by the compiler.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok thanks. So after the if statement, the first declared t is valid again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.