开发者

Time Function Syntax

Why is the time function usually used like this:

time_t currentTime;
currentTime = time( NULL );

instead of this:

time_t currentTime;
time( &currentTime );

Is the first method used more just because it is arguably more readable? Or is there another reason?

Thanks.

Edit: Also, why was the time funct开发者_JAVA百科ion even designed this way? Why have two ways to set the variable?


It always seems to make more sense to return a value from a function than pass a paramter that is changed.

This might be because we learned on languages where functions and subroutines were different, don't know about these youngsters today.


Of course only K&R probably know the true answer, but my suspect is that is just an "incident" because of historical implementation reasons. For example may be the design of this function started as void time(time_t*) because simply wasn't possible in some form of pre-ansi C to return a value of type time_t and only later evolved in a value-returning function.

If this is the explanation then the reason for keeping the parameter anyway is of course backward compatibility with existing code.


The most common format is actually time_t currentTime = time( NULL );

This is shorter, and doesn't leave the currentTime variable uninitialized. The parameter is a historic accident and has no use.


The timer parameter is a pointer to an object of type time_t, where the time value is stored. Alternativelly, this parameter can be a null pointer, in which case the parameter is not used, but a time_t object is still returned by the function.

So you don't need to create a time_t object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜