问题
I've always been curious, why does the time(time_t *) function both return a time_t, and set the time to the passed in pointer?
Example of returning the time:
time_t myTime = time(NULL);
printf("The time is now %s", ctime(&myTime));
Example of setting the value to the pointer:
time_t myTime;
time(&myTime);
printf("The time is now %s", ctime(&myTime));
I originally thought there would be a performance gain by writing to the memory instead of returning, but if it has to do both, doesn't that just make it slower?
回答1:
There's no real benefit in the way it's currently defined.
I suspect that when the time() function was first defined, it used a type that could not be returned from a function. Very early C implementations didn't have long int and were not able to return structures from functions. On a system with 16-bit ints, the only way to represent a time would be as a structure or as an array; 16 bits worth of seconds is less than a day.
So early implementations of time() might have been used something like this (speculation):
time_t now;
time(&now); /* sets now.time_high, now.time_low */
or perhaps:
int now[2];
time_t(now); /* sets now[0], now[1] */
When later C implementations added longer integers and the ability to return structures by value, the ability to return a time_t value from the time() function was added, but the old functionality was kept to avoid breaking existing code.
I think that if time() were being defined today, it would look more like this:
time_t time(void);
I haven't been able to confirm that old implementations of the time() function worked this way (try Googling "time"!), but it makes sense given the history of the language.
If you pass a null pointer to the time() function, it returns the current time without also storing it in a variable; this avoids some of the performance penalty:
time_t now = time(NULL);
回答2:
It allows you to nest a call to time() within another expression, instead of doing it in a separate statement:
time_t x = time(&now) + more_time;
When the above statement finishes, now should contain the current time, and x should contain the current time plus some value.
strcpy falls in the same case because it returns the same char * pointer that has been passed as its destination, so nesting it is possible as well:
printf("Copied string is %s", strcpy(dst, src));
来源:https://stackoverflow.com/questions/9944771/why-does-timetime-t-function-both-return-and-set-the-by-ref