Home > Software engineering >  offsetof macro in c
offsetof macro in c

Time:02-04

#define offsetof(s,m) ((::size_t)&reinterpret_cast<char const volatile&>((((s*)0)->m)))

I've been looking for this code for several minutes and I still don't understand what the const char volatile reference thing is, it's giving me a headache.

#define offsetof(s,m) ((size_t)&(((s*)0)->m))

This one is pretty clear, does make sense and it works well, why is the other one being used by MSVC compiler.

CodePudding user response:

If s::m is of a class type, it could overload operator&, so &(((s*)0)->m) would be the same as (((s*)0)->m).operator&(), which could do something unexpected.

To not use any custom operator&, it is cast to a const volatile char& first (which will have the same address). It needs to be both const and volatile because s::m might be const and/or volatile.

This is how std::addressof would have been implemented before C 11.

CodePudding user response:

The reason that offsetof is in the standard library is that it cannot be written portably. So you’re looking at compiler-specific code. Don’t try to analyze it. Spend your time on more productive pursuits.

  •  Tags:  
  • Related