News for hackers. Stuff that matters.
Re:Ask HN: Favorite pointer tricks in C? by tptacek on Saturday November 20, 2010 @07:50PM (#1925845)
It's a good trick, but I disagree that it's the right way to do it. My preferred idiom looks something like:

  s->field1 = ld32(&cp, ep); 
  s->field2 = ld16(&cp, ep); 
  s->field3 = ld16(&cp, ep); 
  s->field4 = ld8(&cp, ep); 
  s->field5 = ld8(&cp, ep); 
  s->field6 = ld32(&cp, ep); 
 
You can just about automate this with a macro (you need to macro out the structure fields and use them both for the structure declaration and the field expansion), but the extra function call there gives you an opportunity to be defensive about e.g. buffer sizes, never blows up alignment, and isn't appreciably slower.

There are no comments on this comment yet.