Calculation with long variables on left and right since of equal sign

I was under the impression that if there's a long variable on the right side of an expression that the calculation is done with 32b precision but it appears that constant value calculations for partial results are done at 16b unless you specify the constants with a preceeding "L"?

Here's an example program:

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  long motorStartTime = 100000;
  long motorEndTime = motorStartTime + 3 * 60 * 1000;
  Serial.println(motorEndTime);
}

When I compile and run this I get an answer of 83392 because it does the calculation "3 * 60 * 1000" in 16b precision which results in -11072 and then it adds this to 100000 which give 83392.

Since motorStartTime is a long variable, I expected that the compiler would generate code that evaluates the full expression at 32 bits, including the multiplication of the constants.

Is this a compiler bug or is 83392 the "correct", i.e. expected, result?

Thanks,

Dave

such maths are done using int format for your platform (and at compile time when possible) unless you state otherwise
if you are on a uno it means 16 bits. if you are on a MKR or ESP it's 32 bits

➜ on a UNO 3 * 60 * 1000 will overflow

if you enable warnings, you should get a message from the compiler.

See here.

Expected result. The multiplies have higher precedence than the addition so they are done first. If both sides of a multiply are 'int', the result is an 'int'. 3 * 60 = 180. 180 * 1000 won't fit in an 'int' so it gets truncated. That truncated value then gets added to 100000l.

Also see Type Casting (I usually forget the rules for automatic/implicit conversion.)

But with variables the compiler doesn't know the values and you'll just get roll-over (and unexpected results) at run-time.

fair, yes. But with variables you know their type, so you should also know about the max value you can represent and your needs. if you try to fit something that requires 32 bit into 16 bit, then you can expect trouble :slight_smile:

(there are very clear rules on promoting variables to larger types when doing operations with different types in C++)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.