Why does time(time_t *) function both return and set the by-ref?

我怕爱的太早我们不能终老 提交于 2019-11-29 03:28:10

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);

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));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!