Reinitialize timeval struct

2019-04-28 05:16发布

问题:

How can I reinitialize a timeval struct from time.h?

I recognize that I can reset both of the members of the struct to zero, but is there some other method I am overlooking?

回答1:

The completely correct and portable (albeit C99) way to zero-initialize arbitrary (possibly aggregate) types:

myTime = (struct timeval){0};

This works even for structures that contain pointers and floating point members, even if the implementation does not use all-zero-bits as the representations for null pointers and floating point zeros.



回答2:

memset may happen to work on your platform, but it is actually not the recommended (portable) approach...

This is:

struct timeval myTime;

myTime = (struct timeval){ 0 };

memset works because all of the elements of struct timeval happen to have zero values that are represented by the all-zeroes bit pattern on your platform.

But this is not required by the spec. In particular, POSIX does not require the time_t type to be an integer, and C does not require floating-point zero to be represented as all-zero bytes.

Using the initializer syntax guarantees the fields of the structure will be properly set to zero, whether they are integral, floating point, pointers, or other structures... Even if the representation of those things is not all-zero in memory. The same is not true for memset in general.



回答3:

Assuming that you want a struct timeval structure reinitialized to zero values regardless of whether they're floating point types or integral types and regardless of the zero representation for floating point types, a method that will work with C90 or later or C++:

static struct timeval init_timeval;  // or whatever you want to call it

// ...

myTime = init_timeval;

As in R.'s answer and Nemo's answer, this will also handle NULL pointers regardless of how they might be represented. I can't imagine why a struct timeval would have a pointer, but I mention this because the technique is useful for structures other than struct timeval.

The drawback to it in comparison with the other answers is that it requires a static or global variable to be defined somewhere. The advantage is that it'll work with non-C99 compilers.



回答4:

If you're looking for a one-liner, I guess you could also use memset to to the job :

struct timeval myTime;

/* snip ... myTime is now initialized to something */

memset(&myTime, 0, sizeof(timeval)); // Reinitialized to zero


回答5:

You could use memset, then you'd also zero any platform-specific members.