Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It seems like you're responding to something that isn't there -- an accusation along the lines of "... and therefore C is a bad language" or "... and therefore sizeof is poorly designed" or "... and it's bad that the correct answer is 'I don't know'".

The author isn't, so far as I can tell, making any such claim.

He's claiming only this: many people who program in C (or C++, which in this particular respect is the same) think they know that sizeof(...) will be 8, or think they know that sizeof(...) will be 5, and all those people are wrong, because it could be either of those things or various other things too, and there are contexts in which you need to be aware that the assumptions you're inclined to make around this sort of code are wrong.

All of which is straightforwardly correct, so far as I can tell.

As the author says, the question is really about struct padding more than it's about sizeof. It most likely doesn't matter that much whether or not someone knows that sizeof(...) might not be 8 in this situation. But it might matter if, e.g., they read the docs for some binary file format and see that it looks like

  offset type   name
  0000   int    block_size
  0004   char   record_type
  0008   int    user_id
  000C   int    unit_id
  0010   double radiation_level
  0018   int    timestamp
and think "aha, I'll make this neater" and write

  struct protocol_block {
    int block_size;
    char record_type;
    int user_id;
    int unit_id;
    double radiation_level
    int timestamp;
  };
and

  fread(...);
  struct protocol_block * block = buffer;
  int uid = block->user_id;
without being aware that they are making assumptions about what their compiler does with structs (and also about endianness, and other things).


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: