Handmade Hero»Forums»Code
Vjekoslav
9 posts / 1 project
Zero struct initialization
Edited by Vjekoslav on Reason: Initial post
Hi,
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:
1
some_struct Var = {};


I get error if I use that syntax in C compiling with cl. So I use following syntax:
1
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.
1
#define NEW(type, name) type name; memset(&name, 0, sizeof(type));


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


Is there some good practice you would recommend to follow?

Thanks,
Vjekoslav
Mārtiņš Možeiko
2561 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);"