Q:

integer type size issue

#include <ctime>
#include <cstdio>
#include <sys/time.h>
#include <iostream>
using namespace std;

int main() {
    struct timeval tv;
    gettimeofday(&tv, 0);
    unsigned long long int var=tv.tv_sec*1000L+tv.tv_usec/1000L;
    cout<<sizeof(var)<<endl;
    cout<<var<<endl;
    printf("%u%-15u\n", (unsigned int)(var/1000000000), (unsigned int)(var%1000000000));
    return 0;
}

This thing prints
8
1341143123970
1341143123970      

on my 64 bit machine, but
8
1113191712
1113191712      

on my 32 bit server. The second result is evidently clamped to a 32 bit number, but unsigned long long int is 8 bytes on both architectures. Where is the clamping happening then, and why?

A:

It is because the width of long is not the same on your 32-bit and 64-bit machines. The type of tv_sec is an arithmetic type, usually1) long.
You can ensure the multiplication is done with a 64-bit type by using 1000ULL instead of 1000L:
unsigned long long int var=tv.tv_sec*1000ULL+tv.tv_usec/1000ULL;

1) On glibc for example, it is long. "In the GNU C library, time_t is equivalent to long int" http://www.gnu.org/software/libc/manual/html_node/Simple-Calendar-Time.html

