0

Years ago, I asked a question about how to initialize a timespec struct to a zeroed state (nsec and sec equal to zero) with the minimum lines of code.

Many of the responses told me not to use memset, as this was not cross platform compatible and numerous other issues could occur. As a result, I adopted the following way:

struct timeval freshStruct = struct timeval){0};

Years later, I now want to initialize a itimerspec struct, which has within it two timespec structs. One way is for me to do the following:

struct itimerspec alarmTimeFormatted;
alarmTimeFormatted.it_interval = (struct timespec){0};
alarmTimeFormatted.it_value = (struct timespec){0};

I see other answers here on StackOverflow which show using memset to initialize the struct itimerspec this in one line.

So now I'm curious -- is there something different about the itimerspec struct, or are these just bad answers? Is there any eloquent way to initialize the outer / inner structs with just one line?

Thanks

Community
  • 1
  • 1
BSchlinker
  • 3,401
  • 11
  • 51
  • 82
  • I'd use `itimerspec alarmTimeFormatted = { { 0 } };` – Erik Nov 28 '13 at 22:58
  • @Erik -- fantastic. Wasn't aware that would work, but it makes sense. I'm still curious as to the use of memset though and when it is applicable. – BSchlinker Nov 28 '13 at 23:01

1 Answers1

1

It's still bad practice. Erik gave a possible solution in the comments, but usually in C++ we use constructors : itimerspec::itimerspec() : it_interval { 0 }, it_value { 0 } { /***/ }

MSalters
  • 173,980
  • 10
  • 155
  • 350