kaikai said:
I think pointer arithmetic is performed at compile time, so I guess if
the compiler knows the type it may do that.
The compiler *might* do it at compilation time, but it is under no
obligation to do that.
> Do you mean some compilers
will check the object and refuse to do pointer arithmetic when the
object is invalid?
A processor might trap at run time when an invalid address is loaded in
to a pointer variable.
At compile time, if it does the pointer arithmetic at compile time, and
NULL represented as something other than all bits zero the compiler
might suffer from an integer overflow when doing the arithmetic causing
to to produce an incorrect result. Undefined behaviour does not require
a diagnostic, so the compiler could silently produce incorrect code in
this instance and still be conforming.
The point is that it is undefined behaviour so *anything* can happen,
including what you want. However, C has the sizeof operator and the
offsetof macro provided as part of the standard, so you don't have any
need to do such tricks.
Well, on embedded systems you do sometimes have to strange things when,
for example, accessing memory mapped devices, but by then you are well
in to the realms of system specific code anyway so as long as your
compiler guarantees it you are OK.