Reputation: 1254
I couldn't get why this program is giving this output. Is overflow happening here ?
int _tmain(int argc, _TCHAR* argv[])
{
__int64 fileAgeInFileTime ;
fileAgeInFileTime = 24 *60 * 60 ;
cout << fileAgeInFileTime << endl;
fileAgeInFileTime *= 10000000;
__int64 fileAgeInFileTime2 = 24 *60 * 60 * 10000000 ;
cout << fileAgeInFileTime << " " <<fileAgeInFileTime2;
return 0;
}
O/P :
86400
864000000000 711573504
I couldnt understand why fileAgeInFileTime and fileAgeInFileTime2 have different values ?
The real requirement is to get the 100 nano second resolution of file.
Upvotes: 3
Views: 95
Reputation: 2638
Yes, there's an overflow. You multiply four int
constants and assign them to __int64
.
__int64
can be saved inside long long
(long long
should have at least 64 bits since C++11). You need to mark your constants as long long
like this:
__int64 fileAgeInFileTime2 = 24LL * 60LL * 60LL * 10000000LL;
Or mark the first of those constants as LL
, the others are implicitly converted:
__int64 fileAgeInFileTime2 = 24LL * 60 * 60 * 10000000;
Some kind of cast also works (other variables are also implicitly converted):
__int64 fileAgeInFileTime2 = static_cast<__int64>(24) * 60 * 60 * 10000000;
The last line should also explain why
__int64 fileAgeInFileTime2 = 10000000;
fileAgeInFileTime2 *= 24 * 60 * 60;
works. This multiplies four int
s, converts the result to int64
and multiplies it by fileAgeInFileTime2
. The total result is then assign to fileAgeInFileTime2
.
Upvotes: 3
Reputation: 6440
Yes, you have overflow here. When you multiply int
by int
, the result is also int, so you have overflow while calculating 24 * 60 * 60 * 1000000
. After this the incorrect result is stored in __int64
variable.
Here type conversions for arithmetic operators are explained
Upvotes: 2