Search code examples
c++c++-chrono

What happened when constructing a variable of std::chrono::milliseconds from "LLONG_MAX seconds"?


When constructing a variable of std::chrono::milliseconds from "LLONG_MAX seconds", the result t_milli.count() is -1000

auto t_max_seconds = std::chrono::seconds(LLONG_MAX);
auto t_milli = std::chrono::milliseconds(t_max_seconds);

As far as I can see, somehow "-1" came from "LLONG_MAX", and "1000" was the ratio.
(for "microseconds", the result is -1'000'000)

I wonder what happend here, an overflow or undefined-behavior?


Solution

  • You are getting signed overflow in the conversion from seconds to milliseconds.

    On your machine both seconds and milliseconds are represented by signed 64 bit integers. But to convert seconds to milliseconds, the library multiplies by 1000.

    You are effectively doing this:

    cout << LLONG_MAX*1000 << '\n';
    

    which on my machine prints out:

    -1000