What is time(NULL) in C?

后端 未结 8 1100
别跟我提以往
别跟我提以往 2020-12-07 19:12

I learning about some basic C functions and have encountered time(NULL) in some manuals.

What exactly does this mean?

8条回答
  •  难免孤独
    2020-12-07 19:38

    [Answer copied from a duplicate, now-deleted question.]

    time() is a very, very old function. It goes back to a day when the C language didn't even have type long. Once upon a time, the only way to get something like a 32-bit type was to use an array of two ints -- and that was when ints were 16 bits.

    So you called

    int now[2];
    time(now);
    

    and it filled the 32-bit time into now[0] and now[1], 16 bits at a time. (This explains why the other time-related functions, such as localtime and ctime, tend to accept their time arguments via pointers, too.)

    Later on, dmr finished adding long to the compiler, so you could start saying

    long now;
    time(&now);
    

    Later still, someone realized it'd be useful if time() went ahead and returned the value, rather than just filling it in via a pointer. But -- backwards compatibility is a wonderful thing -- for the benefit of all the code that was still doing time(&now), the time() function had to keep supporting the pointer argument. Which is why -- and this is why backwards compatibility is not always such a wonderful thing -- if you're using the return value, you still have to pass NULL as a pointer:

    long now = time(NULL);
    

    (Later still, of course, we started using time_t instead of plain long for times, so that, for example, it can be changed to a 64-bit type, dodging the y2.038k problem.)

    [P.S. I'm not actually sure the change from int [2] to long, and the change to add the return value, happened at different times; they might have happened at the same time. But note that when the time was represented as an array, it had to be filled in via a pointer, it couldn't be returned as a value, because of course C functions can't return arrays.]

提交回复
热议问题