Code:
WINDOWPLACEMENT wplcmt = {sizeof(WINDOWPLACEMENT)};
Looks so much cleaner than:
WINDOWPLACEMENT wplcmt;
memset(&wplcmt, 0, sizeof(WINDOWPLACEMENT));
wplcmt.length = sizeof(WINDOWPLACEMENT);
The assembly output of this thing is also pretty nice, for longer structures MSVC even uses memset
instead of xor eax, eax
and mov
's. And from standard point of view it also looks ok. But I'm still scared about border cases where the structure is not tightly packed say #pragma pack(128)
, and windows suddenly decides to do a memcmp of the structure.
So is it good/bad to use such syntax? Is it good practice to use such initializations?
memset will set the structure to all-bits-zero whereas value initialization will initialize all members to the value zero. The C standard guarantees these to be the same only for integral types, not for floating-point values or pointers. Also, some APIs require that the structure really be set to all-bits-zero.
// In C++ We can Initialize the Variables with Declaration in Structure.
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).
The second code you show,
WINDOWPLACEMENT wplcmt;
memset(&wplcmt, 0, sizeof(WINDOWPLACEMENT));
wplcmt.length = sizeof(WINDOWPLACEMENT);
is beyond horrible. Obfuscation, inefficiency, verbosity, you crammed it all into that.
The first code snippet,
WINDOWPLACEMENT wplcmt = {sizeof(WINDOWPLACEMENT)};
is, except for the obfuscation, the preferred way, unless you want to
spend more time needlessly writing more code,
have readers spending more time reading and needlessly analyzing your verbose code,
get less efficient execution, and
provide bug entry portals.
By the way, what's with the obfuscated name you used, wplcmt
?
Why are you obfuscating names?
Is your question real or is it simply trolling?
Cheers & hth.,
EDIT: the question has been edited. The above questions were in response to the original title/question, "How evil is this structure allocation?". I'm leaving my answer as-is to provide context for the comments.
EDIT 2: the context has changed even further: the OP's nick changed from "Madman" to "Coder". So, while the original was about "How eveil is" normal code by "Madman", it's now about "Is it preferred..." by "Coder". Oh well, I mean, I'm not calling him "Madman" in the commentary, as it would appear now; it's what he called himself, his nick at the time.
Use memset. Then everyone immediately sees what the code does and it's very unlikely to have any unexpected side-effects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With