0

I recently came across this code and thought it was a little overkill.

struct Structure {
  unsigned int first;
  unsigned int last;
};
(std::size_t)&((Structure *)0)->last; // 4

So I'm wondering if I can safely do:

sizeof(unsigned int); // 4

instead of:

(std::size_t)&((Structure *)0)->last; // 4

or what that code is doing anyway if it's so much better.

EDIT

That code more or less euqals to offsetof as pointed out in https://stackoverflow.com/a/1379370/1001563 If you know what you're searching for you'll find the answer without having to ask. Thanks to @VladfromMoscow

Community
  • 1
  • 1
noob
  • 8,982
  • 4
  • 37
  • 65
  • 1
    Now add an `unsigned char middle;` between `first` and `last`. `(std::size_t)&((Structure *)0)->last` will now likely (not guaranteed) be 8. How would you update your `sizeof(unsigned int)` to give the right result here? –  Oct 18 '14 at 11:01
  • are you really 18 years old ? –  Oct 18 '14 at 11:10

1 Answers1

3

Programs are usually being changed. So it is better to use a general approach. For example the type of data member first can be changed or before data member last there can be added one more data member. Take into accpunt that there is already a similar macro in C defined in <stddef.h> (or <cstddef> in C++)

offsetof(type, member-designator)
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • doesnt the code actually output size of pointer of type of variable `last` inside `Structure`? If so, it is size of pointer on given machine, and that cant change unless you move the code to another computer/OS – Creris Oct 18 '14 at 10:57
  • @Creris The code outputs the offset of data member last within the structure. – Vlad from Moscow Oct 18 '14 at 10:59
  • Great so the best practice for something like this would be: `offsetof(Structure, last)`? – noob Oct 18 '14 at 11:07
  • @mic Yes, it is better to use standard features. – Vlad from Moscow Oct 18 '14 at 11:08
  • 1
    Another advantage is that in the general case, if your structure is not `__attribute__((packed))` then you cannot know that its offset within the structure is the sum of the size of the preceding elements. – abligh Oct 18 '14 at 11:27