This is kind of a trivial question since I have several workarounds, but maybe there's another syntax that avoids the problem.
I defined a long variable to hold number of seconds in a day and wanted to initialize it to 24 hours (forget about the rationale that lies behind this). To document better what I'm doing I coded it as:
long variable = 60*60*24;
The result is that the computation is done using int and results in a truncated value of 20864 due to overflow. I get that. I can solve this by coding:
long variable = 60*60*24.;
OR
long variable = 60*60; variable = variable*24;
I find it strange that the compiler, knowing the result is a long, does the calculation as an int.
As a side note:
If compiled for an Arduino Uno, there is no indication of an error.
If compiled for another device (in this case a Microchip AVR-IoT Cellular using DXCore), the compiler actually provides a warning error.
That's common behaviour in many languages. Overflows in calculations don't increase the operand size in expressions. An eventual target (assignment...) type is only checked after evaluation.
Cast one operand to (long) or 24L and evaluation is done with long numbers.
Your problem is accompanied by anonymous variable names. Fix that at the same time:
const long SECS_PER_MIN = 60L;
const long MINS_PER_HOUR = 60L;
const long HOURS_PER_DAY = 24L;
const long SECS_PER_DAY = SECS_PER_MIN * MINS_PER_HOUR * HOURS_PER_DAY;
bulletproof, and it's so self explanatory, it doesn't need comments. It also "cooks up" a few other conversion constants you might find handy somewhere in your code.
void setup() {
long variable = 60L*60L*24L;
Serial.begin(115200);
delay(100);
Serial.println(variable);
}
void loop() {
// put your main code here, to run repeatedly:
}
Not in this case, but in other cases it could. I gave the generic answer. I will grant you that the number of seconds in a minute isn't likely to change any time soon.