AhmedYzab AhmedYzab - 4 months ago 30
C++ Question

Addition between Integer and Float.... resulting in a Zero

I have been doing an operation in C++ on the timer struct of Linux provided by the interface "clock_gettime(CLOCK_MONOTONIC, &CurrentTime)"

#include <iostream>
#include <time.h>

int main()
struct timespec CurrentTime;
CurrentTime.tv_sec = 28220;
CurrentTime.tv_nsec = 461189000;

unsigned long long TimeNow;
TimeNow = (28220 * 1000000) + (461189000 * 0.001);

std::cout << TimeNow;

yet the result always giving TimeNow as a Zero.

I would appreciate if any has answer to this question or a lead to follow.
It was done using GCC Compiler

Code Snipped could be found here


In the line:

TimeNow = (28220 * 1000000) + (461189000 * 0.001);

the (28220 * 1000000) part is calculated using ints, and (with 32-bit int) overflows giving an incorrect value (likely -1844771072).

The (461189000 * 0.001) part is calculated using doubles, because of the 0.001 double constant, giving 461189.0 as a double.

The two are then added together, giving a negative double value... when that negative double is converted to unsigned long long for the assignment to TimeNow, it's being converted as 0, probably because that's the closest value in its range to any negative number. This is different from converting a negative integer type to unsigned, which would "wrap around".