Search code examples
arduinoesp32arduino-c++

C++ ESP32 - 86400000000 is printed as 500654080


I'm working on a ESP32 using Arduino, for some reason the values are printed differently, what is the cause?

auto reset_time = 24L * 60 * 60 * 1000 * 1000; //86400000000

  Serial.print("Reset Timer in: ");
  Serial.println(reset_time);

  Serial.print((reset_time / 1000));
  Serial.println(" ms");

  Serial.print((reset_time / 1000 / 1000));
  Serial.println(" s");

  Serial.print((reset_time / 1000 / 1000 / 60));
  Serial.println(" m");

  Serial.print((reset_time / 1000 / 1000 / 60 / 60));
  Serial.println(" h");

This produces the following output:

21:05:58.310 -> Reset Timer in: 500654080
21:05:58.310 -> 500654 ms
21:05:58.310 -> 500 s
21:05:58.310 -> 8 m
21:05:58.310 -> 0 h

Solution

  • 86400000000 Mod 2^32 is 500654080.

    The value is larger than fits in a 32 bit int; what you see is the remainder.

    If I read a C17 draft correctly, a constant expression that cannot be represented in its type is a constraint violation. It requires a diagnostic message from the compiler:

    6.6 Constant expressions
    Constraints
    [...] 4 Each constant expression shall evaluate to a constant that is in the range of representable values for its type.

    5.1.1.3 Diagnostics
    1 A conforming implementation shall produce at least one diagnostic message (identified in an implementation- defined manner) if a preprocessing translation unit or translation unit contains a violation of any syntax rule or constraint,