4 ms·
I didn't understand why you would want to write that code. To me, a struct is a (very very mild) abstraction, since there can be padding added for alignment and
by unwind 7y ago
I didn't understand why you would want to write that code. To me, a struct is a (very very mild) abstraction, since there can be padding added for alignment and if you don't need to know about each field's offset, then you shouldn't care.
So just write
memset(&a, 0, sizeof a);
and be done, that will zero any padding too and end up just doing the right thing. It's also very clear to the compiler what you're after, and I wouldn't be at all surprised if a compiler chose not to call memset() for this, and just does the equivalent of
a.x = 0;
a.y = 0;
or perhaps, by knowing about padding, doing a properly-sized single write to both fields at once.
- tumult 7y agoWhy is beside the point. I'm not making a judgment about morality or motivation. I said that one of the few concrete examples in the blog post was factually wrong. It shouldn't be used as an example for the point the author is trying to prove. Also, for proving the point of the blog post, the example you showed instead would have been wrong in the same way as the original example from the blog post. The point was about writing to the (theoretical) padding between fields. Your example would still have written to this padding (if it existed) in the same way. And if this padding did exist, it still wouldn't have been illegal, in either example.
- saagarjha 7y ago> that will zero any padding too and end up just doing the right thing No, it will not; the compiler can and occasionally will transform this into two writes that don't touch padding. It is surprisingly difficult to actually zero out padding bits. (However, your code is better than the one mentioned above, as it does correctly zero out the structure's members.)
- SAI_Peregrinus 7y agoA more useful example would be struct { char a; char b; char c; }a; memset(&a, 0, 2 * sizeof(char)); IE trying to clear only part of a struct using memset. Clearly not a great way to do things.
- mark-r 7y agoDid you miss the part where writing to a padding byte might generate an error on some architectures? Granted I don't know of any such architectures, but C was designed to work on just about any weird thing you can dream up.