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?
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.