Handmade Hero»Forums»Code
TM
13 posts
implementing offsetof yourself vs stddef.h
Just wanted to say that technically the way casey implemented offsetof himself on stream is not portable. If you check stddef.h, you might or might not see exactly what casey wrote, but that doesn't mean that it is portable.
The people that wrote stddef.h know whether it is ok to dereference a null pointer like that for that specific compiler, so it is ok for them to use it. But for a newer version of the compiler that might change, and they might change the implementation of offsetof.
For gcc for example there is a builtin compiler keyword for offsetof, which is being used inside stddef.h.

My point is, the same piece of code is ok inside stddef.h, but in your usage code it isn't portable, if you want the code to work with different compilers.
Also technically it is undefined behavior according to the standard, so implementing it yourself is making use of an undocumented compiler "feature".

I'm not saying that it is bad to implement offsetof yourself, just wanted you to know what implications it has if you decide to do so :)
Casey Muratori
801 posts / 1 project
Casey Muratori is a programmer at Molly Rocket on the game 1935 and is the host of the educational programming series Handmade Hero.
implementing offsetof yourself vs stddef.h
Nothing we implement on stream is portable by your definition here, however. If you look at the actual C++ spec, there are tons of things like this where it says the compiler is allowed to do whatever it wants to do if you do thing X - for example, any operation involving two pointers that come from different memory areas is allowed to break completely.

As I said early-on in Handmade Hero, I don't think there is any point to programming along these lines. You might as well write in Java or something for all the flexibility the C++ spec actually allows if you try to follow it to the letter. The only thing you can reasonably program in in C++ is by following what compilers actually do in practice.

- Casey