Reinitialize timeval struct

允我心安 提交于 2019-12-05 05:37:39

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.

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.

Michael Burr

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.

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!