I’m reading about the initialized values by default of an array/struct and have this question:
is memset(&mystruct, 0, sizeof mystruct) same as mystruct = { 0 }; ?
if it’s not, what’s difference?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No.
… will tell the compiler to call a function that we expect will set during execution the data in mystruct to zero.
… will set tell the compiler set by itself the data to zero, which means it will:
Note that perhaps the compiler could optimize the memset into a compile-time instruction (like replacing the first version with the second version), but I wouldn’t rely on that as
memsetis a function from the runtime library, not some language intrinsic (I’m not a compiler writer/language lawyer, though).Coming from C++, my own viewpoint is that the more you can do at compilation and the more the compiler knows at compile time, before the execution even starts, the better: It enables the compiler to possibly optimize the code and/or generate warning/errors.
In the current case, using the
mystruct = { 0 };notation to initialize astructis always safer than using the memset because it is very very easy write the wrong thing in C with amemsetwithout the compiler complaining.The following examples show that it is easy for the code to do something different than it appears to do: