1

This question is similar to the following:

convert epoch to time_t

Converting time_t to int

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!

BuvinJ
  • 10,221
  • 5
  • 83
  • 96

2 Answers2

4

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)
Galik
  • 47,303
  • 4
  • 80
  • 117
  • Excellent. I failed to understand that I could just assign an std::time_t to 0. This answered my question as posted. I'm giving the edge to Remy though, for his suggestion of using -1, which is better than my original plan. – BuvinJ May 03 '18 at 00:54
3

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Thanks! I'm going with your -1 suggestion. That is better than 0. That happily compiled too. – BuvinJ May 03 '18 at 00:55