Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I clear structs using a template; saves copying and screwing up the length:

template <class C> SPL_INLINE_FORCE void Zero(C &c) { memset(&c, 0, sizeof(c)); }

struct tm tm_struct;

Zero(tm_struct);



There's also a way to do this without any user-defined functions that works in both C and C++:

    struct tm tm_struct = { 0, };


In ISO C++ and GNU C you can also omit the 0:

    struct tm tm_struct = { };


Does that work on char array members in the struct?


Yes, as far as I believe, this should always work in standard C89/C99. In the char array case, it works due to the brace elision rule in aggregates: assuming

    struct foo { char bar[3]; };
These declarations are equivalent:

    struct foo f1 = { 0, };
    struct foo f2 = { { 0, } };


In C, using: struct tm tm_struct = { 0 } ;, the rest of the struct including padding is initialized to zero bits.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: