Handmade Hero»Forums»Code
Vjekoslav Krajačić
9 posts
Zero struct initialization
Edited by Vjekoslav Krajačić on Reason: Initial post
is it the case that there's no a standard way of zero initializing struct that is guaranteed to work on all compiler implementations for C?
Series use this form:
some_struct Var = {};

I get error if I use that syntax in C compiling with cl. So I use following syntax:
some_struct Var = { 0 };

But can this type of initializing bite me in the future? Would it be safer to memset the struct each time? Maybe even create a small macro for it? Something along these line.
#define NEW(type, name) type name; memset(&name, 0, sizeof(type));

One could create new structs like this then:
NEW(Var, some_struct);

Is there some good practice you would recommend to follow?

Mārtiņš Možeiko
2376 posts / 2 projects
Zero struct initialization
Doing { 0 } or doing explicit memset is OK to do. Just be careful about macro's. As they may not to do something correctly if you pthem in wrong place - like "if (foo) NEW(int, x);"