Skip to main content
Inspiring
January 13, 2014
Question

Initialising Structs vs AEFX_CLR_STRUCT()

  • January 13, 2014
  • 1 reply
  • 722 views

Just out of curiosity I decided to initialise a struct with empty curly braces, e.g. PF_ParamDef my_param = {};

When debugging it was confirmed that by doing this it initialised everything in the struct to zero (the memory used by the struct was fully zeroed). Surely this is a faster way of clearing a struct than with the macro AEFX_CLR_STRUCT(), right? AEFX_CLR_STRUCT does this explicitly using a while loop to set every byte in the struct to zero, so the end result is valid.

IMO this is a much nicer way of declaring struct variables, since you also get to initialise it immediately, which is considered good practice.

Christian

This topic has been closed for replies.

1 reply

January 14, 2014

Yes, even if many people doubt it, you can safely do this, in C++ at least (not in C).

http://stackoverflow.com/questions/60653/is-global-memory-initialized-in-c/60707#60707

http://stackoverflow.com/questions/1069621/are-members-of-a-c-struct-initialized-to-0-by-default

If you want to fast clear a struct (consisting only of PODs (=plain old datatypes) by filling it with zeros, don't necessarily use the AEFX_CLR_STRUCT() macro, a simple memset command will work better: memset(&x,0,sizeof(x))Just don't do this on classes or non-POD structs!

But since C++ default value initialisation can partially also be done at compile time (while memset and others only at runtime), I'd recommend doing the "struct x = {}" approach anyway!

Please refer to this link for more info:

http://stackoverflow.com/questions/1998752/which-one-to-use-memset-or-value-initialization-to-zero-out-a-struct

I would recommend always doing proper initialisation/clearing, just to avoid confusion or quirky compilers, as there is no performance hit by doing so.

Another note: don't rely on the debugger in debug mode to check for initial values, as in debug mode, structs are usually set to 0 after creation anyway.

If you really want to be sure what values are in a struct after initialisation, compile in release mode with full optimisation on and then output the struct values