Reinitialize timeval struct

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

I understand that I can reset so that both elements of the structure are zero, but is there any other method that I skip?

+5
source share
5 answers

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

myTime = (struct timeval){0};

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

+10
source

memset may work on your platform, but this is actually not a recommended (portable) approach ...

:

struct timeval myTime;

myTime = (struct timeval){ 0 };

memset , struct timeval , all-zeroes .

. , POSIX , time_t , C , - .

, , , , , ... , memset .

+3

, , struct timeval , , , C90 ++

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

// ...

myTime = init_timeval;

R. answer Nemo answer, NULL , . , struct timeval , , , struct timeval.

The disadvantage to it compared to other answers is that it requires a static or global variable to be defined. The advantage is that it will work with compilers other than C99.

+1
source

If you are looking for a single line, I think you can also use memset for the job:

struct timeval myTime;

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

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

You can use memset, then you would also need to reset any platform related members.

-1
source

All Articles