Reputation: 11114
This question is similar to the following:
but I don't quite have my answer there.
If you want to get the current date/time you can call time(0)
or time(NULL)
like in the following standard example:
// current date/time based on current system
time_t now = time(0);
I want to define a function which will return a time_t and allows the client to pass an optional default return value in the event of an error. Further, I want to set a default on that "default" argument. This provides symmetry within a library I have with one-to-one counter parts across several languages, so I'm not looking to redesign all that.
My thought was to set the default return to the epoch. Then, a client could in theory easily evaluate that return, and decide that an epoch coming back was more than likely (if not always) an indication of it being invalid. I can think of some alternatives, but nothing clean, that also fits my existing patterns.
Is there a short and sweet way to make my function signature have a default value for this object equal to the epoch? For instance
...myfunc(...., const time_t &defVal=time(0) );
would be perfect if 0
meant the epoch rather than the current date/time!
Upvotes: 1
Views: 2658
Reputation: 598448
What is wrong with using 0
? (time_t)0
represents the epoch itself (if you want to find the actual epoch date/time, pass (time_t)0
to gmtime()
or localtime()
).
time_t myfunc(...., time_t defVal = 0 );
Or, you could use (time_t)-1
instead, which is not a valid time, as time()
returns (time_t)-1
on error, and time_t
represents a positive number of seconds since the epoch.
time_t myfunc(...., time_t defVal = (time_t)-1 );
Either way provides the user with something that is easily compared, if they don't provide their own default value.
Upvotes: 3
Reputation: 48675
The function std::time()
returns the number of seconds since the epoch as a std::time_t
. Therefore to find zero seconds after the epoch set std::time_t
to zero:
std::time_t t = 0;
So you could do something like:
void myfunc(const std::time_t& defVal = 0)
Upvotes: 4