0
  • How to check if a time_t variable is initialized?
  • If I want to compute the difference of two time_t vars with the difftime function, do I need to manually perform any sanity checks before invokation?
  • Also, since the difftime return value is a double, how do I check that this value is greater than 0.0?

Thanks

alex
  • 121
  • 3
  • 9
  • If you are the one doing the coding, you should know if a variable is initialised. Else, as a general principle, sanity checks are always your responsibility if you do not entirely control input. To check for greater than 0.0, do if (difftime(t2, t1) > 0.0) { //your code}. – clarasoft-it Jul 22 '16 at 13:55

2 Answers2

1

How to check if a time_t variable is initialized?

There really isn't a way to check if it has been initialized. If it wasnt initialized it can be any random value which happened to reside in is memory location. You should program in a way that you know it is initialized.

If I want to compute the difference of two time_t vars with the difftime function, do I need to manually perform any sanity checks before invokation?

I don't think so. Since time_t is an integer type it is always in a valid state (integers do not have a nan or inf state like floating points), therefore I see no reason you would get an invalid output. I guess you could check that the values of the time_t make sense given the context of the prolbem you are solving. Such as it might not make sense to have one refer to a time 2000 years ago.

Also, since the difftime return value is a double, how do I check that this value is greater than 0.0?

Use an if statement. if(dt > 0.0) {...}

chasep255
  • 11,745
  • 8
  • 58
  • 115
  • Sanity check: Perhaps `t != -1`. -1 is the error return value from `time()`. BTW `time_t` is _not_ defined by C to be an integer value. It must be some integer or FP type. – chux - Reinstate Monica Jul 22 '16 at 17:58
0

READ THIS: cppreference page on time_t

Very usable information since cppreference also covers C.

  1. Basically, time_t is often implemented as 64-bit integer. Which means default initialization is same for time_t as is for plain old int. You don't have to "initialize" it to store values in it.

  2. As always in C, you can't really check if you have made some bad operation on an integer value that sets it to something practically unusable but still valid - meaning no, just make sure to not let any variables go uninitialized.

  3. with difftime > 0. Why would it not work? double can accurately represent integer values up to ~100,000,000,000,000. That is a time difference of 3 million years.

Puzomor Croatia
  • 781
  • 7
  • 16