1
#ifndef UNICODE 
#define UNICODE
#endif

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <Windows.h>

int main()
{
    char buffer[30];
    int counter=0;

    for(int i=0; i<22 ; i++)
    {       
        Sleep(1000);
        printf("%d %d\n",counter++,time(0));
    }

    system("pause");
    return 0;
}

This version works fine, it outputs counter and the timestamps of the last 22 seconds. Unfortunately, when I did seemingly extraneous thing - replacing counter and time(0) , that is printf("%d %d\n",time(0),counter++); , function always printed 0 in place of counter! Any explanation of this strange fact?

0x6B6F77616C74
  • 2,559
  • 7
  • 38
  • 65

3 Answers3

3

time() returns type time_t, which is 64 bit on many platforms, while "%d" refers to int which is mostly 32bit.

mity
  • 2,299
  • 17
  • 20
2

The %d format specifier means that printf is expecting an int type. But time() returns a time_t; if that's bigger than an int, then more stuff will be put on the stack than printf is expecting, essentially offsetting the position of all subsequent arguments (so the upper bytes of the time value are interpreted as the second argument, in your case).

(To confirm, you should compare sizeof(int) and sizeof(time_t).)

For potential solutions, see the answers to e.g. this question: What primitive data type is time_t?.

Community
  • 1
  • 1
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
1

The result of time() (on Windows at least) is a 64-bit integer. You must use a format other than %d to print it. Try %lld.

It worked when the time was last because you got the lower 32 bits, since Intel is a little-endian processor.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622